n&(n-1)

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

数据对比(uint_16 n;)

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

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

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

2                    0000000000000010               1                                0000000000000001                0000000000000000

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

4                    0000000000000100               3                                0000000000000011                0000000000000000

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

16                  0000000000010000               15                              0000000000001111                0000000000000000

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

100                0000000001100100               99                              0000000001100011                0000000001100000

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

128                0000000010000000               127                             0000000001111111                0000000000000000

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

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;
}
时间: 2024-08-06 14:53:28