表示数字的最小位数

Mar*_*rka 4 c# integer bit-manipulation bit

找出代表一些随机int数需要多少位的最有效方法是什么?例如,数字30,000表示二进制

111010100110000

所以它需要15位

pet*_*kyy 9

你可以尝试:

Math.Floor(Math.Log(30000, 2)) + 1
Run Code Online (Sandbox Code Playgroud)

要么

(int) Math.Log(30000, 2) + 1
Run Code Online (Sandbox Code Playgroud)


Hen*_*rik 7

int v = 30000; // 32-bit word to find the log base 2 of
int r = 0; // r will be lg(v)

while ( (v >>= 1) != 0) // unroll for more speed...
{
  r++;
}
Run Code Online (Sandbox Code Playgroud)

有关更高级的方法,请参见http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious

请注意,这会计算最左侧设置位的索引(对于30000,为14).如果你想要比特数,只需加1.