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

‘’’
def check_bit4(input):

num = bin(input)

mask = 0b1000

desired = mask & inut

if desired > 0:

return "on"

else:

return "off"

‘’’
Hi, I was wondering why does the num valuable messes up the code, since once I remove it and replace it with input in the & operation, it works as it should.
Thanks for your help

bin() takes in an integer and converts it into binary, but it is in string format. So num takes on a string and Python is unable to compare a string and a binary using &.

However, Python does allow you to use & to compare between an integer and a binary. After you removed num and replaced it with input in the & operation, input, which is an integer, is now being compared with mask, a binary.

And so the code works.