Search code examples
python-3.xbinarylogical-operators16-bit

Logical expression that can catch i'th bit in 16-bit binary that corresponds to an integer value?


I'm currently working on the last project in Nand2Tetris course.
I've been trying to figure out how the logic expression works while implementing a bit-wise calculation.

How Python can catch the right digits of 16-bit binary that correspond to an integer y when the twoToThe[i] == 0 (5 is 101 in binary, thus twoToThe[0] == 0 and twoToThe[2] == 0 are False and it's the right answer)
but why does not show the exact opposite result when twoToThe[i] == 1?
I thought it would return True on both twoTwoThe[0] == 1 and twoTwoThe[2] == 1

Here's code below

# Calculating x * y
x = 3 # doesn't matter here
y = 5
# Array that holds i'th bit's integer values in 16-bit binary (e.g. twoToThe[4] = 16)
twoToThe = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768]

## Set twoToThe[i] == 0
print(y & twoToThe[0] == 0) # False (101 is 5, so False is right)
print(y & twoToThe[1] == 0) # True
print(y & twoToThe[2] == 0) # False (101 is 5, so False is right)
print(y & twoToThe[3] == 0) # True
print(y & twoToThe[4] == 0) # True
print(y & twoToThe[5] == 0) # True
...
print(y & twoToThe[15] == 1) # False


## Set twoToThe[i] == 1
print(y & twoToThe[0] == 1) # True
print(y & twoToThe[1] == 1) # False
print(y & twoToThe[2] == 1) # False (I expected True here, but it's false)
print(y & twoToThe[3] == 1) # False
print(y & twoToThe[4] == 1) # False
print(y & twoToThe[5] == 1) # False
...
print(y & twoToThe[15] == 1) # False

Solution

  • The y & twoToThe[0] expressions evaluates to a new integer (as a result of a bitwise and operation between the bits of 5 and the bits of twoToThe[i]), not to a boolean as I think you were expecting. Check it:

    y = 5
    # Array that holds i'th bit's integer values in 16-bit binary (e.g. twoToThe[4] = 16)
    twoToThe = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768]
    
    print(type(y & twoToThe[0])) #int
    
    print(y & twoToThe[0]) # 1
    print(y & twoToThe[1]) # 0
    print(y & twoToThe[2]) # 4
    print(y & twoToThe[3]) # 0
    print(y & twoToThe[4]) # 0
    print(y & twoToThe[5]) # 0