C++编程技巧—对数运算实现

可以调用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; }
             
}


posted @ 2015-05-24 16:42  cyjseagull  阅读(1702)  评论(0编辑  收藏  举报