Bitwise operations

Bitwise operations can sometimes look like some abstract hocus pocus. But if you take the time to get to understand the ins and outs, you’ll see that they can be very useful in some specific occasions.

Here I have explained some basic operations and their use:

Bit shifting

This means moving the bits to the left or to the right, removing the bits on the side where the bits are being moved to adding zeros to the opposite side.

0001 << 2 results in 0100        // moved 2 places to the left
1000 >> 3 results in 1 (or 0001) // moved 3 places to the right
The AND operator

The AND operator can be used to check whether a bit at a specific position has a value of 1.

Let’s say we would like to check if a value A has 1 at position 3 (from the right), we construct a value X which has zeros at all positions, except for the position we want to check (in this case the third), where it has a 1.

A: 00010100       01010011
X: 00000100 00000100
&-------- &-------- 00000100 00000000
(>0 => true) (==0 => false)

Since a 0 in an AND operation will always result in 0, all the positions where value X has a 0 will therefore result in 0.

The position where X has a 1 will only result in 1 if A has a value of 1 at that same position.

The XOR operator

The XOR operator can be used to toggle a bit at a specific location.

If we want to toggle the bit at a specific location in value A, we construct a value X, which has all zeros, except for the location we want to toggle.

A: 00010100   01010011
X: 00000100 00000100
^-------- ^-------- 00010000 01010111