How do I check if a specific bit is on or off?


#1

Question

How do I check if a specific bit is on or off?

Answer

If a specific bit is on, it will result in a 1 in that position when ANDed together with a mask containing a 1 in that position and 0s everywhere else. For example, if we wanted to check if the 0th bit is on, we’d write:

input = 0b1010
mask = 0b0001
desired = input & mask

if desired > 0:
  print “it’s on!”
else:
  print “it’s off!”

Our mask has only one bit turned on, since that’s the only position we’re looking for to be on. Once we AND it with our input, only that position can possibly be a 1, since AND requires both inputs to be True, or 1. That’s why in the example above we get it’s off! printed to the console.


FAQ: Learn Python - Introduction to Bitwise Operators - The Man Behind the Bit Mask