getBit 函数没有给出正确的结果

getBit function not giving correct result

Python 中的以下 getBit 函数是,如果在索引 i 处设置了一个位,则获取 True,如果它为 0,则获取 False。

def getBit(num, i):
    return ((num & (1 << i)) != 0)

对于以下测试用例,我得到如下输出:

print(getBit(1011, 2))
print(getBit(1011, 1))
print(getBit(11011, 3))
print(getBit(1011, 3))

False
True
False
False

前两个输出正确,后两个错误。代码有什么问题? (1 << 3) 确实给出了 8,但是在 1011 上它并没有给出 1,因为在第三个位置。

测试用例不正确。您取的是 1011 的第三位,用二进制表示为 0b1111110011。可以看到,第三位是0.

def getBit(num, i):
    print ("{0:b}".format(num))
    binary_positional_value = (num & (1 << i))
    return binary_positional_value != 0

print(getBit(1011, 3))

1111110011
False

但你认为 1011 是二进制表示。这样做会像这样:

print(getBit(0b1011, 3))