A bit mask is just a variable that aids you with bitwise operations. A bit mask can help you turn specific bits on, turn others off, or just collect data from an integer about which bits are on or off.
num = 0b1100 mask = 0b0100 desired = num & mask if desired > 0: print "Bit was on"
In the example above, we want to see if the third bit from the right is on.
- First, we first create a variable
numcontaining the number 12, or
- Next, we create a
maskwith the third bit on.
- Then, we use a bitwise-and operation to see if the third bit from the right of
desiredis greater than zero, then the third bit of
nummust have been one.
Define a function,
check_bit4, with one argument,
input, an integer.
It should check to see if the fourth bit from the right is on.
If the bit is on,
return "on" (not
If the bit is off,
Check the Hint for some examples!