n&(n-1)

1. 判断一个正整数是否为2的乘方数

    数据对比(uint_16 n;)

-------------------------------------------------------------------------------------------------

n         n 的二进制表示           (n - 1)    (n-1) 的二进制表示        n&(n - 1)

-------------------------------------------------------------------------------------------------

2       0000000000000010b    1        0000000000000001b    0000000000000000b

-------------------------------------------------------------------------------------------------

4       0000000000000100b    3        0000000000000011b    0000000000000000b

-------------------------------------------------------------------------------------------------

16     0000000000010000b    15      0000000000001111b     0000000000000000b

-------------------------------------------------------------------------------------------------

100   0000000001100100b    99      0000000001100011b     0000000001100000b

-------------------------------------------------------------------------------------------------

128   0000000010000000b    127    0000000001111111b      0000000000000000b

-------------------------------------------------------------------------------------------------

 

 

 unsigned char isPower(unsigned int n)

{
    return(((n == 0)  || (n & (n-1))) ? 0x00 : 0x01);
}

 

2. 判断一个正整数转化为二进制后数字 “1” 的个数

unsigned char NumOfOne(unsigned int n)
{
    unsigned char i = 0;
    while(n)
    {
        n &= n-1;
        i++;
    }
    return i;
}

 

posted @ 2017-01-13 16:50  Waming  阅读(391)  评论(0编辑  收藏  举报