calculate number of bits set in byte

前端 未结 11 2189
抹茶落季
抹茶落季 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:27

    The usual answer for "fastest way to do bitcount" is "look up the byte in an array". That kind of works for bytes, but you pay an actual memory access for it. If you only do this once in awhile, it is likely the fastest, but then you don't need the fastest if you only do it once in awhile.

    If you do it a lot, you are better off batching up bytes into words or doublewords, and doing fast bitcount operations on these. These tend to be pure arithmetic, since you can't realistically lookup a 32 bit value in an array to get its bitcount. Instead you combine values by shifting and masking in clever ways.

    A great source of clever tricks for doing this is Bit Hacks.

    Here is the scheme published there for counting bits in 32 bit words in C:

     unsigned int v; // count bits set in this (32-bit value)
     unsigned int c; // store the total here
    
     v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary
     v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     // temp
     c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
    

提交回复
热议问题