The Man Behind the Bit Mask


#1

Hi,

A question.

In the code below why does the mask need to be 0b1000 and not 0b0100 or 0b0001?

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

Thank you.


#2

Hi @objectsolver83948,

Whenever input and mask each contain at least one 1 in the same position, the & operation will produce a result, which we save as desired, that is greater than 0. We only want a result that is greater than 0 when input has a 1 in the fourth bit from the right, regardless of wherever else there might be a 1 in input. Therefore, mask needs to have a 1 in that position, and 0 everywhere else.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.