Bit Operations
And operation
The and operation x & y produces a number that has one bits in positions where
both x and y have one bits. For example, 22 & 26 = 18, because
10110 (22)
& 11010 (26)
& 11010 (26)
= 10010 (18)
Using the and operation, we can check if a number x is even because x & 1 =0
if x is even, and x & 1 = 1 if x is odd. More generally, x is divisible by 2k
exactly
when x & (2k ‒ 1) = 0.
Or operation
The or operation x | y produces a number that has one bits in positions where at
least one of x and y have one bits. For example, 22 | 26 = 30, because
10110 (22)
& 11010 (26)
& 11010 (26)
= 11110 (30)
Xor operation
The xor operation x ^ y produces a number that has one bits in positions where
exactly one of x and y have one bits. For example, 22 ^ 26 = 12, because
10110 (22)
& 11010 (26)
& 11010 (26)
= 01100 (12)
Not operation
The not operation ~x produces a number where all the bits of x have been
inverted. The formula ~x = ‒x ‒ 1 holds, for example, ~29 = ‒30.
The result of the not operation at the bit level depends on the length of the
bit representation, because the operation inverts all bits. For example, if the
numbers are 32-bit int numbers, the result is as follows:
x = 29 00000000000000000000000000011101
~x = ‒30 11111111111111111111111111100010
~x = ‒30 11111111111111111111111111100010
Bit shifts
The left bit shift x << k appends k zero bits to the number, and the
right bit shift x >> k removes the k last bits from the number. For example,
14
<< 2 = 56, because 14 and 56 correspond to 1110 and 111000. Similarly, 49 >> 3 = 6,
because
49 and 6 correspond to 110001 and 110.
Note that x << k corresponds to multiplying x by 2k, and x >> k
corresponds
to dividing x by 2k rounded down to an integer.