You are on page 1of 3

# THIS IS WRITTEN BY SRIDHAR from karimnagar, any doubts mail me on muthojusridhar_495@yahoo.

com Bit manipulation and shifting is the process of taking data and toying with the binary representation of the number (the basic 1s and 0s that it is made of). Bit operations in C/C++ are carried out with the following operators:
-----------------------------------------------------------| Operator Definition | -----------------------------------------------------------| || | Bitwise OR (Not to be conused with ||) | |& | Bitwise AND (Not to be confused with &&) | |^ | XOR (Exclusive OR) | | << | Shift left | | >> | Shift right | | ~ | Unary (One's compliment) | ------------------------------------------------------------

OR is fairly simple: The OR operator ( | ) compares two bits and returns true ( 1 ) if either or both bits are set to true.
A=1;B=2;C=A|B; A 00000001 B 00000010 ----------C 00000011

It basically just adds the binary of the numbers. It doesn't actually add the numbers though: remember that. AND is just as easy: The AND operator ( & ) compares two bits and returns true ( 1 ) only if both bits are set to true.
A=1;B=3;C=A&B; A 00000001 B 00000011 ----------C 00000001

See what it did? Everywhere there was a 1 in the first string and the second string, there was a 1 in the resulting string. XOR is slightly trickier: The XOR operator ( ^ ) compares two bits and returns true ( 1 ) if and only if one of the bits is set to true. (1 ^ 3)
A=1;B=3;C=A^B; A 00000001 B 00000011 -----------

htm#&panel1-2 . is that the numbers don't carry! soo: 000000001 >> 1 = 00000000 (the result is not 10000000 as you might expect) And remember I wrote the numbers out in binary instead of the actual numbers you'd put in there.vignanam. you don't write the numbers in binary -. it became a zero.C 00000010 Anywhere there was a 1 in both numbers.B=~A. http://www. UNARY is the easiest.org/telugu. ( 00000011 is 3. and 00000001 is 1 binary ) So remember.you write them in decimal to use the bit operators. 00000010 is 2. It basically means binary opposite: (~1) A=1. It moves the numbers down by the number you place to the right. >> is actually the quickest way to divide by 2 << is actually the quickest way to multiply by 2 Another thing about shifts. A 00000001 ----------B 11111110 << and >> (shift left and right) are incredibly simple. and they are used the most: 000000010 >> 1 = 000000001 000000001 << 1 = 000000010 It basically goes like this: number >> amount to shift by.