【发布时间】:2019-12-31 14:33:58
【问题描述】:
以下 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
【问题讨论】:
-
当我以二进制打印这些数字时,它们似乎是正确的。您是否希望输入位于 base2 而不是 base10 中?
-
是的,我确实想要它在 base2 中,我应该只使用 bin()
-
这不是更容易吗
return str(num)[i] == '1'? -
打印 (getBit(0b1011, 3))
-
@Marcos 没有使用它,因为索引超出范围给出 False 即 0 直接例如。 getBit(0b1011, 4),所以我们不需要使用掩码来处理它
标签: python python-3.x bit-manipulation bit