求32位int二进制下最左边的bit '1'

来源:互联网 发布:云霄生活网络 编辑:程序博客网 时间:2024/05/22 10:41

源地址:http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn

java 里就是用的这种方法。

#include <iostream>using namespace std;typedef unsigned int uint32_t;uint32_t highestOneBit(uint32_t v){    static const int MultiplyDeBruijnBitPosition[32] =         {            0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,            8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31        };    v |= v >> 1; // first round down to one less than a power of 2     v |= v >> 2;    v |= v >> 4;    v |= v >> 8;    v |= v >> 16;        return MultiplyDeBruijnBitPosition[(uint32_t)(v * 0x07C4ACDDU) >> 27];}int main(){    cout <<"1 :" <<highestOneBit(1) << endl;    cout << "4 :" << highestOneBit(4) << endl;    cout << "1024 :" << highestOneBit(1024) << endl;    cout << "1023 :" << highestOneBit(1023) << endl;     return 0;}

这种更容易理解:
#include <iostream>using namespace std;typedef unsigned int uint32_t;uint32_t highestOneBit(uint32_t v){ static const char msb_256_table[256] =     {        0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,        4, 4, 4, 4, 4, 4, 4, 4,4, 4, 4, 4,4, 4, 4, 4,        5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,       6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,       6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,       7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,        7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,       7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,       7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,    };    int result = 0;    if (v  > 0xFFFF)      {       v  >>= 16;       result += 16;    }    if (v  > 0xFF)      {       v  >>= 8;       result += 8;    }    return (result + msb_256_table[v]);}int main(){    cout <<"1 :" <<highestOneBit(1) << endl;    cout << "4 :" << highestOneBit(4) << endl;    cout << "1024 :" << highestOneBit(1024) << endl;    cout << "1023 :" << highestOneBit(1023) << endl;     return 0;}


原创粉丝点击