This item was added on: 2003/01/17

Credit: -KEN-

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
-----------
C 00000010

Anywhere there was a 1 in both numbers, it became a zero. UNARY is the easiest. It basically means binary opposite:

(~1)

A=1;B=~A; 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. 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, 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. ( 00000011 is 3, 00000010 is 2, and 00000001 is 1 binary ) So remember, you don't write the numbers in binary -- you write them in decimal to use the bit operators.For more details on bitwise operators, go to our tutorial on bitwise operators in C++.

You can also read about our bit manipulation FAQ.

Credit: -KEN-