Sunday, January 4, 2009

3: Bit Manipulation (check the bit and flip the bit)

In the previous post, we already learn how to set the bit and clear the bit. To check whether the k-th bit is 0 or 1 we can use & operator. To flip(change from 0 to 1 or 1 to 0) the bit simply use ^ (XOR) operator. This is the last series from "Trilogy Of Bit Manipulation".


int x = 10; // 00001010

// check the bit
if( (x & (1<<3)) != 0 )
printf("3-th bit is 1");
else
printf("3-th bit is 0");

// flip the bit
x = x ^ (1<<3); // long version
printf("%d\n",x); // x = 2 = 00000010

// flip the bit again
x ^= (1<<3); // short version
printf("%d\n",x); // x = 10 = 00001010

No comments:

Post a Comment