【问题标题】:getBit function not giving correct resultgetBit 函数没有给出正确的结果
【发布时间】: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


【解决方案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
假的

但您认为 1011 是二进制表示。可以这样做:

print(getBit(0b1011, 3))

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 2015-11-12
    • 2012-08-30
    相关资源
    最近更新 更多