COUNTING SET BITS IN A BYTE
Probably to count set bits in a byte or in 4 bytes will be most frequent asked question in the interview. Fortunately, I found four solution.
- The mask and shift approach.
- The Brian Kernighan approach.
- The index into an array approach.
- The MIT HACKMEM approach.
Make and Shift
unsigned char countbits_shift_method (unsigned char b)
{
unsigned char mask, count;for (count = 0, mask = 0×80; mask != 0; mask >>= 1)
{
if (b & mask)
count++;
}return (count);
}
Brian Kernighan
unsigned char countbits_bk_method (unsigned char b)
{
unsigned char count;for (count = 0; b != 0; count++)
{
b &= b – 1; // this clears the LSB-most set bit
}return (count);
}
Index into an Array
unsigned char parity_array [256] =
{ 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, … };
// Note that you need to fill-in this arrayunsigned char countbits_array_method (unsigned char b)
{
return (parity_array [b]);
}
MIT Hack Memo
int BitCount(unsigned int u)
{
unsigned int uCount;uCount = u
- ((u >> 1) & 033333333333)
- ((u >> 2) & 011111111111);
return
((uCount + (uCount >> 3))
& 030707070707) % 63;}
Discussion Area - Leave a Comment