A Developer's Diary

Jun 28, 2010

Bit Operations

There are six bitwise operators used in the C programming language.

AND Operator &

Truth Table
0 & 0 = 0
1 & 0 = 0
0 & 1 = 0
1 & 1 = 1

OR Operator |

Truth Table
0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1

XOR Operator ^

Truth Table
0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0

NOT Operator ~

Truth Table
~0 = 1
~1 = 0

Right Shift Operator >>

Left Shift Operator <<

Note:
A unary operator is one which operates on a single operand where as a binary operator is one which operates on two operands


Mask
A mask is a bit pattern with some bits set to on (1) and some bits set to off (0)

Turning Bits On

number = number | MASK;
OR
number |= MASK;

This sets on all the bits that are 1 in the MASK

Turning Bits Off

number = number & ~MASK;
OR
number &= ~MASK;

This sets off all the bits that are 1 in the MASK

Toggling Bits

number = number ^ MASK;
OR
number ^= MASK;

This toggles values corresponding to 1s in the MASK

Comparing a Bit value

Checking if the value of bit at position p is set or not

number = 9
binary = 1 0 0 1
position = 1
mask = 1 0 0 0

if( ( number & mask ) == mask ) printf(" bit is set ");


Read more ...