你可以尝试:
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)
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.