可以調用C、C++中現成的算法庫實現整數對數運算,比較高效的64位整數對數運算實現方法如下:
int Log2(uint64_t n)
{
int result;
if( n & 0xffffffff00000000) { result +=32; n >>= 32; }
if( n & 0x00000000ffff0000) { result +=16; n >>= 16; }
if( n & 0x000000000000ff00) { result +=8; n >>= 8; }
if( n & 0x00000000000000f0) { result +=4; n >>= 4; }
if( n & 0x000000000000000c) { result +=2; n >>= 2; }
if( n & 0x0000000000000002) { result +=1; n >>= 1; }
}