Bitwise Operation in C++

1. If we want to know whether one bit of this number is zero:

// i_index: the index of rightmost bit is 0
bool IsZero(int i_number, unsigned int i_index)
{
return ((i_number & (1 << i_index)) == 0);
}

2. If we want to know the exact value of one bit:

// i_index: the index of rightmost bit is 0
int GetOneBit(int i_number, unsigned int i_index)
{
int temp = i_number;
temp = temp >> i_index;
temp = temp & 1;
return temp;
}

3. If we want to know the value of several bits:

unsigned int GetBits(unsigned int i_input, unsigned int i_start, unsigned int i_end)
{
assert(i_start <= i_end);
// create mask
unsigned int mask = ((1 << (i_end – i_start + 1)) – 1) << i_start;
// use AND to get bits, then remove all the 0s on the right
unsigned int r = (i_input & mask) >> i_start;

return r;
}

4. Set one bit to one:

void SetBit(int& value, unsigned int i_index)
{
value |= (1 << i_index);
}

5. Set one bit to zero

void ClearBit(int& value, unsigned int i_index)
{
value &= ~(1 << i_index);
}

6. Find first set bit:

unsigned int FindFirstSet(int value)
{
unsigned int pos = 0;
if ((value& 0xFFFF) == 0)
{
value>>= 16;
pos += 16;
}
if ((value& 0xFF) == 0)
{
value>>= 8;
pos += 8;
}
if ((value& 0xF) == 0)
{
value>>= 4;
pos += 4;
}
if ((value& 0x3) == 0)
{
value>>= 2;
pos += 2;
}
if ((value& 0x1) == 0)
pos += 1;
return pos;
}

7. Find how many set bits in a number:

unsigned int SetBitCount(int value)
{
unsigned int count;
for (count = 0; value; count++)
{
value &= (value – 1);
}

return count;
}

Leave a Reply