问题描述
我目前正在处理 Nand2Tetris 课程的最后一个项目。
我一直在尝试弄清楚逻辑表达式在实现按位计算时是如何工作的。
当 y
(5 是二进制的 101,因此 twoToThe[i] == 0
和 {{1} } 是 twoToThe[0] == 0
,这是正确的答案)
但是为什么在 twoToThe[2] == 0
时没有显示完全相反的结果?
我认为它会在 False
和 twoToThe[i] == 1
True
代码如下
twoTwoThe[0] == 1
解决方法
y & twoToThe[0]
表达式计算为一个新整数(作为 5
位和 twoToThe[i]
位之间的按位和运算的结果),而不是像 I 那样的布尔值以为你在期待。检查一下:
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