DEV Community

Nihal Islam
Nihal Islam

Posted on

Bit Manipulation (Part 1)

As computers only understand 0 and 1 or we can say only binary number, we need to understand how these numbers work.

There are a few Bitwise operations such as, AND (&), OR (|), XOR (^), NOT (~), Left Shift (<<), Right Shift (>>). AND, OR and XOR operations can be performed between two values, and NOT, LS and RS operations are performed for only one value.

AND Operation

If we perform AND operation the answer would be 0 if any one of the two bits is 0. Otherwise the answer would be 1.

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

OR Operation

Same as AND operation. However, here if 1 exists in between two bits, then the answer would be 1. Otherwise 0.

0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1

XOR Operation

Here, if both bits are same, then the answer would be 0, otherwise 1.

0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0

NOT operation

Performing NOT operation will gives us the opposite of the existed bit. For example, if we perform NOT operation to bit 1, then it will give us 0.

~0 = 1
~1 = 0

The operations will also work if we have more than one bits. For example,

Bit Operation

Left Shift Operation

Left shift operation shifts the bits by i position. For instance,

1111 << 3 = 1000

Here, after shifting the value by 3 position, 3 bits from left side is removed and 3 bits of value 0 is added on the right.

Right Shift Operation

Pretty much the same as left shift. Here instead of shifting left, bits will be shifted right. I am just giving an example,

0111 >> 3 = 0000

Top comments (0)