我在Windows上使用python 2.7,numpy 1.6.1、32位。我正在编写一个函数,将一些数据打包为32位整数,并从常量值生成C源声明。这样做时,我发现numpy的uint8类型有些奇怪的行为。
我敢肯定,没有人会惊讶于此:
>>> n = 0x94 << 24
>>> n
2483027968L
>>> hex(n)
'0x94000000L'
但是用numpy uint8进行同样的操作,您会得到一些令我惊讶的东西:
>>> n = np.uint8(0x94) << 24
>>> n
-1811939328
>>> hex(n)
'-0x6c000000'
有人会认为,显式无符号的类型返回负值的可能性甚至更低。
请注意,带符号位清除的值按预期工作:
>>> n = np.uint8(0x74) << 24
>>> n; hex(n)
1946157056
'0x74000000'
我碰巧注意到numpy似乎正在将无符号类型提升为有符号类型:
>>> n = np.uint8(0x74) << 24
>>> type(n)
<type 'numpy.int32'>
这似乎是一个明显的错误。我找不到对这种已知错误的引用,但是...是吗?
numpy
似乎将右手参数(24
)视为原始宽度的有符号整数(int32
在您的情况下,int64
在我的情况下)。
看起来将uint8
gets提升为相同类型,并且移位的结果也为相同类型:
>>> np.uint8(0x94) << 56
-7782220156096217088
>>> type(np.uint8(0x94) << 56)
<type 'numpy.int64'>
将右手参数设置为无符号int
可得到您期望的结果:
>>> np.uint8(0x94) << np.uint(56)
10664523917613334528
>>> type(np.uint8(0x94) << np.uint(56))
<type 'numpy.uint64'>
>>> hex(np.uint8(0x94) << np.uint(56))
'0x9400000000000000L'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句