Saturday, January 3, 2009

2: Bit Manipulation (clear the bit)

In the first series you have learn how to set the bit, now you will learn how to clear the bit.
This is the second series from "Trilogy Of Bit Manipulation".


int x = 0;
x |= (1<<2); // x = 00000100
x |= (1<<4);


To clear the k-th bit, we can use & and ~ operator.
x = x & ~(1<<2); // I clear the 2-th bit.
How does it work ?
& is AND operation:
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0

~ is NEGATE operation:
~ 1 = 0
~ 0 = 1


x = x & ~(1<<2); // long version
x &= ~(1<<2); // short version


initial x = 17 = 00010001
and I want to clear the 0-th bit.

(1<<0) = 00000001
~(1<<0) = 11111110

00010001
11111110
-------- AND operation
00010000 (the 0-th bit is clear)

1 comment: