Hacker symbol

January 11, 2020 ~ 1 min read

Check if bit is on


Something neat I learned today. If you want to check if a bit is toggled inside an int here how it is done:

valueToCheck&(1<<bitPostion) > 0

The way this works is because of the following:

valueToCheck := 0x04 // 0000 0100
shiftLeft := 1<<3 // 0000 0100
val := valueToCheck&shiftLeft // 0000 0100 & 0000 0100 = 0000 0100
val > 0 // true because the result of AND is a binary number greater than 0

valueToCheck := 0x14 // 0001 0100
val := valueToCheck&shiftLeft // 0001 0100 & 0000 0100 = 0000 0100
val > 0 // true because the result of AND is a binary number greater than 0

valueToCheck := 0x1b // 0001 1011
val := valueToCheck&shiftLeft // 0001 0100 & 0001 1011 = 0000 0000
val > 0 // false because the result of AND is a 0 in binary

With shiftleft we create a binary variable that has a single bit turned on at the position we want. Then the AND only allows that single bit to be saved in the resulting val. If that single bit is the resulting then the value will be greater than zero.


Sebastian BolaƱos

Hi, I'm Sebastian. I'm a software developer from Costa Rica. You can follow me on Twitter. I enjoy working on distributed systems.