DEV Community

Nihal Islam
Nihal Islam

Posted on

Bit Manipulation (Part 2)

There are certain things we can do with bitwise operators. These operations are useful for coding interviews. I am just quickly showing an example of how we can use these bitwise operators.

Check ith Bit

Checking the ith bit means to check whether the ith bit of a value is 0 or 1. For instance, if a value is 001010101 and we want to know the 3rd bit, then the answer would be 0 and 0th bit would be 1. Remember i starts from 0 and it starts from right side.

By using Left shift and AND operator, we can find the ith bit of a value. An example is given below,

(1 << 0) & 13 = 1
(1 << 1) & 13 = 0
(1 << 2) & 13 = 4
(1 << 3) & 13 = 8

Here, 13 in binary is 1101 and 1 in binary is 0001. Left shifting 1 by ith position will give us a value where the bit 1 is on the ith position and all the other bits are 0. For example if we left shift 0001 by 2 position, it will look like this 0001 << 2 = 0100. So, performing AND operation between (1 << i) and and 13 will give us either 0 or some other number. If it is 0 then we can say the ith bit is 0, otherwise 1.

Bit Operation

if (((1 << i) & value) > 0) {
    ith bit is 1;
} else {
    ith bit is 0;
}
Enter fullscreen mode Exit fullscreen mode

You get the idea. There are many things we can do such as update ith bit, clear ith bit, check whether a number is power of 2 or not, etc.

Top comments (0)