C provides six bitwise operations. They can apply to integer data type only, including char, short, int and long. The advantage of using bitwise operators is speed. It generally makes your program faster.

The six bitwise operators are,
&  AND (eg. 0011&0101 = 0001)
|  OR (inclusive, eg. 0011|0101 = 0111)
^  XOR (exclusive, eg. 0011^0101 = 0110)
~  ONE'S COMPLEMENT(unary, eg. ^01 = 10)
<<  LEFT SHIFT
>>  RIGHT SHIFT

The right operands for shift operators must be non-negative. For example, x >> 2 will shift the variable x right by 2 digits, which is equivalent to multiply the variable by 4. A worth-noting point for shift operators is that if the left operand is unsigned, zeros will be fit into the vacated bits. While for signed, it’s machine-dependent, some use zeros, some use the sign bit. The applications for bitwise operators,

To "set" a bit (where n is the bit number, and bit 0 is
the least significant bit):
unsigned char a |= (1 << n);
To "clear" a bit:
unsigned char b &= ~(1 << n);

 

To "toggle" a bit:
unsigned char c ^= (1 << n);
To "test" a bit:
unsigned char e = d & (1 << n);
To check a variable is even or odd:
var&1, if it's true, then var is odd, otherwise, it's even.

 


To swap two variables (This is cool!):
int a, int b;   a = a^b; b = a^b; a = a^b;
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.