calculate number of bits set in byte

前端 未结 11 2220
抹茶落季
抹茶落季 2020-12-09 18:58

I am interested, which is the optimal way of calculating the number of bits set in byte by this way

template< unsigned char byte > class BITS_SET
{
pub         


        
11条回答
  •  生来不讨喜
    2020-12-09 19:20

    Why not do a left shift and mask off the rest?

    int countBits(unsigned char byte){
        int count = 0;
        for(int i = 0; i < 8; i++)
            count += (byte >> i) & 0x01; // Shift bit[i] to the first position, and mask off the remaining bits.
        return count;
    }
    

    This can easily be adapted to handle ints of any size by simply calculating how many bits there is in the value being counted, then use that value in the counter loop. This is all very trivial to do.

    int countBits(unsigned long long int a){
        int count = 0;
        for(int i = 0; i < sizeof(a)*8; i++)
            count += (a >> i) & 0x01;
        return count;
    }
    

提交回复
热议问题