The Basics

At the heart of bit manipulation are the bit-wise operators&(and),|(or),~(not) and^(xor). The first three you should already be familiar with in their boolean forms (&&,||and!). As a reminder, here are the truth tables:

A B !A A && B A \ \ B A ^ B
0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 1 0

The bit-wise versions of the operations are the same, except that instead of interpreting their arguments as true or false, they operate on each bit of the arguments.

Thus, if A is 1010 and B is 1100, then

  • A & B = 1000
  • A | B = 1110
  • A ^ B = 0110
  • ~A = 11110101 (the number of 1′s depends on the type of A).

The other two operators we will need are the shift operators

a << b and a>> b. The former shifts all the bits in a to the left by b positions; the latter does the same but shifts right.

results matching ""

    No results matching ""