Help i dont understand this code


#1

in an excersie, they had sample code

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

hoes does the test>0 work. wouldnt the result always be yes. thx


#2

Any number that has 8 as an addend (bit-4) will satisfy this conditional. Consider what each bit represents in a binary number:

high order bit        low order bit
       1      0      0      1
2  ^   3      2      1      0

0b1001  =>  9
0b1000  =>  8
0b1000  =>  9 & 8

If we are confined to 4 bits, then we can conclude that the group of numbers that satisfy the relation are in the top half of 16 numbers in the sample set. Lower half, 0..7; upper half, 8..15.


#3

It helps if we conceive of the idea of AND being a mimic of multiplication.

1 0 0 1
1 0 0 0
| | | + 1 * 0 => 0 ----+
| | +-- 0 * 0 => 0 --+ |
| +---- 0 * 0 => 0 + | |
+------ 1 * 1 => 1 | | |
                 | | | |
                 1 0 0 0

See anything interesting?