Todays post gonna be super exciting! This is something that gave me quite hard time to understand when I was learning them for university contest. Lets dig in.

We know that we have 10 base number system from 0, 1 .. to .. 9. But for computer it's just 0 & 1 (which are called bit) and even if we have a integer variable like value := 13 , internal bit representation looks like 1101 for 13

Bitwise operator allows us to directly manipulate and work with those bit. Here's a quick intro to these operators and what they does:

Bitwise AND (&), OR (|), XOR (^)

These are similar to logical operators (eg. &&, || ) however unlike them there result is not boolean. As we do these operations between two integer, although in bit level, outcome is just another integer. Following is the chart of each operations outcome:

For example when we do each of above operations between 12 and 7 this is what happens:

<< — image here —>>

Quick Tip: when we do a XOR (^) operation between two same number they results 0

<< —  explanation of find single from duplicate list — >>

Left Shift (<<) && Right Shift (>>)

Shifting operation shifts the bits position for given times. Left shift (<<) shifts to shift bit position to left side and right shift (>>) shifts bit position to right side.

For example if I take an integer 2 whose bit representation is 10 and do a left shift operation 2<<1 , which means shift the 2's bit 1 time to left side, result would be 100.

Similarly if I take integer 5 whose bit representation is 101 and do a right shift operation 5>>2 , which means shift the 5's bit 2 times to right side and result would be 001

Use case