getBit函数未给出正确的结果

2024-06-16 09:46:57 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

前2个输出正确,但后2个输出错误。代码有什么问题(1<&书信电报;3) 给8,但在1011,它不给1,因为在第3位


Tags: 函数代码ltfalsetruereturndef错误
1条回答
网友
1楼 · 发布于 2024-06-16 09:46:57

测试用例不正确。您将获取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))

相关问题 更多 >