Saturday, January 3, 2009

1: Bit Manipulation (set the bit)

In 32-bit Compiler, int size is 4 byte (32 bit).
Today we will play with bit ( I will type the last 8 bit rather than 32 bit to simplify my explanation).
This is the first series from "Trilogy Of Bit Manipulation".


int x = 0;
//The bit value is : 00000000 (all the bit is 0).


 
x = x | (1<<0); // set the 0-th bit from right.
// The bit value is : 00000001 (the last bit is 0).

 
x = x | (1<<2); // set the 2-th bit from right.
// The bit value is : 00000101.

How does it work ?

| is OR operation :
1 or 1 = 1
1 or 0 = 1
0 or 1 = 1
0 or 0 = 0

<< is Shift Left operation :
1<<0 = 1 = 00000001
1<<1 = 2 = 00000010
1<<2 = 4 = 00000100
1<<3 = 8 = 00001000

So when I have x = 10 = 00001010

And I want to set the 5-th bit:
x = x | (1<<5); // long version
x |= (1<<5); // short version


x = 10 = 00001010
1<<5 = 32 = 00100000
OR operation-----------
00101010

No comments:

Post a Comment