如何计算 32 位数字在分块为字节时将占用的字节数

How to calculate the number of bytes a 32-bit number will take when chunked into bytes

所以我们要将 32 位整数分成 8 位块:

var chunks = [
  (num & 0xff000000) >> 24,
  (num & 0x00ff0000) >> 16,
  (num & 0x0000ff00) >> 8,
  (num & 0x000000ff)
]

在计算块之前,您如何知道有多少块?基本上我想知道在将它分块到数组之前它是 1、2、3 还是 4 个字节。关于 32 位整数的一些位技巧或其他东西。

function countBytes(num) {
  // ???
}

我可以想到几种方法,具体取决于您的偏好and/or代码库风格。

第一个比另一个使用更多的分析数学,并且可以执行比下面的按位数学差一点:

// We will need a logarithm with base 16 since you are working with hexadecimals
const BASE_16 = Math.log(16);
const log16 = (num) => Math.log(num) / BASE_16;

// This is a function that gives you the number of non-zero chunks you get out
const getNumChunks = (num) => {
  // First we grab the base-16 logarithm of the number, that will give us the number of places 
  // you need to left-shift 16 to get your number.
  const numNonZeroes = Math.round(log16(num));
  // We need to divide that number by 2 since you are grabbing bits by two
  const numChunks = Math.ceil(numNonZeroes / 2);
  
  return numChunks;
}

第二个严格按位:

const getNumChunks = (num) => {
  let probe = 0xff;
  let numChunks = 0;
  while ((probe & num) || num > probe) {
      probe = probe << 8;
      numChunks++;
  }
  
  return numChunks;
}

JSFiddle here

或者这一行使用 clz32 函数来确定 32 位 unsigned int 中有多少字节被使用...

function numOfBytes( x ) {
    return x === 0 ? 1 : (((31 - Math.clz32( x )) / 8) + 1) | 0;
}