# The Man Behind the Bit Mask

#1

Can I just check the fourth position to see if it’s on, like checking a specific index in a list. Instead of assigning 1000 as a prerequisite. Assuming you get a bit-number 11011 for instance.

``````def check_bit4(input):
if input > 0:
return "on"
else:
return "off"``````

#2

Yes, technically you can. BUT you have to do some type casting to convert it into a binary and then string. Then you can get at the bits of a string just like you did previously when iterating through the characters of a name.

``````bits = 0b1010
bitsStr = str(bin(bits)) # This is a string representation of the binary 0b1010

print bits  # //-> 10
print bin(bits) # //-> 0b1010
print bitsStr # //-> '0b1010'

# Here is where you can select a specific character
# in the string starting from the end of the string.
print bitsStr[-4] # //-> '1'
``````

Therefore, yes, technically you can, however, that’s not the most efficient nor readable way of checking bit state.

Instead, use a mask `0b1000` and then follow the example that is given.

#3

Very interesting – thank you for your response. Greatly appreciated!

#4

Have a look on the following code
def check_bit4(input):
num = int(bin(input),2)
#print type(num)