Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate number of bits set in byte

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
{
public:
    enum {
     B0 = (byte & 0x01) ? 1:0,
     B1 = (byte & 0x02) ? 1:0,
     B2 = (byte & 0x04) ? 1:0,
     B3 = (byte & 0x08) ? 1:0,
     B4 = (byte & 0x10) ? 1:0,
     B5 = (byte & 0x20) ? 1:0,
     B6 = (byte & 0x40) ? 1:0,
     B7 = (byte & 0x80) ? 1:0
    };
public:
 enum{RESULT = B0+B1+B2+B3+B4+B5+B6+B7};
};

Maybe it is optimal when value of byte is known at run-time? Is it recommended use this in code?

like image 564
dato datuashvili Avatar asked Mar 30 '12 20:03

dato datuashvili


People also ask

How many bits are set in a byte?

We all know that 1 byte comprises of 8 bits and any integer or character can be represented using bits in computers, which we call its binary form(contains only 1 or 0) or in its base 2 form.

How do you calculate the number of bits?

Well, you just have to calculate the range for each case and find the lowest power of 2 that is higher than that range. For instance, in i), 3 decimal digits -> 10^3 = 1000 possible numbers so you have to find the lowest power of 2 that is higher than 1000, which in this case is 2^10 = 1024 (10 bits).

How many bytes is a bit in C?

A byte is typically 8 bits. C character data type requires one byte of storage. A file is a sequence of bytes.

How many bits are set in an integer in C?

int a = 3, then 3 will be represented in binary with 32 bits.


1 Answers

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
like image 111
Ira Baxter Avatar answered Sep 19 '22 17:09

Ira Baxter