Thursday, February 25, 2010

Bit manipulation techniques

Some simple bit manipulation techniques
Set a bit: x |= (1 << position);
Clear a bit: x &= ~(1 << position);
Toggle a bit: x ^= (1 << position);
Test a bit: ((x >> position) & 1) != 0)
Test if power of two: ((x & (x - 1)) == 0)
Divide 'x' by 2 'n' times: x = x >> n;
Multiple 'x' by 2 'n' times: x = x << n;
Swap two numbers:
void swap(int& a, int& b)
{
a ^= b;
b ^= a;
a ^= b;
}


No comments:

Post a Comment