Bitwise operations can be performed on either integers or chars.
The << operator shifts bits n bits to the left and the >> operator shifts bits n bits to the right. Here are several examples assuming that integers are 8 bit quantities:
i = 6 // i = 00000110 i = i << 3 // i = 00110000 (48 in base 10) i = 86 // i = 01010110 i = i << 3 // i = 10110000 (176 in base 10) -- leftmost 3 bits thrown away i = 86 // i = 01010110 i = i >> 3 // i = 00001010 (10 in base 10) -- rightmost 3 bits thrown away i = 6 // i = 00000110 i = i >> 3 // i = 00000000 -- rightmost 3 bits thrown awayNotice that the left shift operator throws away the leftmost three bits and adds three 0 bits at the end of the string. Similarly, the right shift operator "throws away" the rightmost three bits and adds three 0 bits to the beginning of the string. In general, left shifting by n bits throws away the leftmost n bits and adds n 0 bits to the right side of the string (thus multiplying the string by 2n). Similarly, right shifting by n bits throws away the rightmost n bits and adds n 0 bits to the left side of the string (thus dividing the string by 2n).
The bitwise logic operators perform bitwise logic operations on each pair of bits in the two operands. There are three bitwise logic operators:
The truth tables for these three operators are as follows:
|
|
|
Here are some examples:
0110 | 1010 = 1110 0110 & 1010 = 0010 0110 ^ 1010 = 1100To see how each of these results get computed, put the second operand under the first, like you might do in an arithmetic operation:
0110 | 1010 ---- 1110 0110 & 1010 ---- 0010 0110 ^ 1010 ---- 1100
In a real program, you might actually write:
int a = 6; // a = 0110 int b = 10; // b = 1010 int c = a | b; // c = 1110 (14 in base 10)
You will see that there are many uses for bit manipulation operations as you proceed through your computer science courses. Here are a few uses in this course: