How do I check if a specific bit is on or off?
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!”
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
AND requires both inputs to be
1. That’s why in the example above we get
it’s off! printed to the console.