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

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.

4 Likes

HI, why is that wrong?

def check_bit4(bit):
  bit = int()
  mask = 0b1000
  desi = bit & mask
  
  if desi > 0:
    return "on"
  else:
    return "off"

If you use the int() method without a parameter it is returning 0 as default.
Delete this line from the code and it will be fine.

1 Like

remove bit = int()
it should be ok