If we want to check whether a particular bit is on/off, then the mask should have a 1
in that bit and 0
’s in all the other bits. The 0
’s will ensure that the other bits are not taken into consideration when making our decision (because 0 & 1
as well as 0 & 0
will result in 0
, so we are purposely ignoring all the other bits by zeroing them).
The mask should have a 1
in the bit that we want to check.
If the input
has a 0
in that specific bit, then 0 & 1
will result in 0
. Since we have already ignored all the other bits, so the final result will be 0
.
If the input
has a 1
in that specific bit, then 1 & 1
will result in 1
. Since we have already ignored all the other bits, so the final result will be non-zero (the exact result depends on the bit we wanted to check).
Consider the following:
input = 0b101001100
mask = 0b1000 # Want to check 4th bit
result = input & mask
print(result) # 8 (Non-Zero Result because 4th bit of input is 1)
input = 0b101001100
mask = 0b100 # Want to check 3rd bit
result = input & mask
print(result) # 4 (Non-Zero Result because 3rd bit of input is 1)
# If the particular bit is 1, then the & will give a non-zero result. The exact
# result depends on the position of the bit.
input = 0b1010001
mask = 0b1000 # Want to check 4th bit
result = input & mask
print(result) # 0 (Zero Result because 4th bit of input is 0)
If we just wanted to check the 4th bit and no other bits, then technically we could have written the condition as:
if desired == 8:
return "on"
else:
return "off"
But, suppose we had a second parameter in our function for specifying which bit we want to check, then the following could work:
def check_bit(num, position):
mask = 1 << (position - 1)
desired = num & mask
if desired > 0:
return "on"
else:
return "off"
print(check_bit(0b101001101, 1)) # on
print(check_bit(0b101001101, 2)) # off
print(check_bit(0b101001101, 3)) # on
print(check_bit(0b101001101, 4)) # on
print(check_bit(0b101001101, 5)) # off
print(check_bit(0b101001101, 6)) # off
print(check_bit(0b101001101, 7)) # on
Just specifying the condition if desired > 0:
as non-zero gives a more general condition (works for any bit), as opposed to if desired == 8:
(works only for 4th bit).