Another "The Man Behind the Bit Mask"


#1

Task: It should check to see if the fourth bit from the right is on.

def check_bit4(input):
mask=0b1000
cresult=input & mask
if cresult > 0 :
    return "on"
else:
    return "off"

This code above works, but initially I had it set to

if cresult == 1

and it fails. Why is it that it works with bigger than, but not with equals to?


#2

nevermind... I ran some tests:

>>> mask=0b1000
>>> input=0b1
>>> print mask * input
8
>>> print bin(mask * input)
0b1000
>>>

#3

Good on you for figuring it out :smile:

In order to make the answer clearer for others who come to this thread at a later point in time:

Why is it that it works with bigger than, but not with equals to?

Because a successful (input & 0b1000) will give "8" (0b1000) and not "1" (0b0001). So it'll work with either "cresult == 8" or with "cresult > 0". The latter will be more flexible when you start working with varying masks later on.


#4

My code is simple and it worked
def check_bit4(inout):
if inout >>3 >0:
return "on"

else:
    return "off"

print check_bit4(0b01000)