【问题标题】:Left shifting a Python integer yielding incorrect result左移 Python 整数会产生不正确的结果
【发布时间】:2017-04-19 20:19:48
【问题描述】:

谁能解释一下这个 Python 代码是怎么写的:

print "bits_received:", bits_received
tmp = 0
print type(tmp)
tmp = (1 << bits_received)
print type(tmp)
print "tmp: 0x{:X}".format(tmp)

可能会产生这样的结果:

bits_received: 95
<type 'int'>
<type 'numpy.int64'>
tmp: 0x80000000

【问题讨论】:

  • bits_received 是一个 NumPy 标量。 NumPy 整数是固定宽度的,就像 C 一样。看起来 NumPy 正在为您提供底层 C 编译器的左移行为(这可能是底层机器的左移行为),而不是引发错误。

标签: python python-2.7 type-conversion bit-shift


【解决方案1】:

user2357112 正确:

bits_received: 88 <type 'int'>
bits_received: 95 <type 'numpy.int64'>

bits_received 变量的类型从 int 更改为 numpy.int64,通过添加另一个 numpy 类型的变量.int64。将其他变量包装在“int(...)”中解决了我的问题。

谢谢,user2357112!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2015-10-12
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多