Python 为什么移动numpy uint8会产生负值?

Python 为什么移动numpy uint8会产生负值?,python,numpy,Python,Numpy,我在windows上使用的是python 2.7、numpy 1.6.1和32位。我正在编写一个函数,将一些数据打包成32位整数,并从常量值生成C源声明。在这样做的过程中,我在numpy的uint8类型中发现了一些奇怪的行为 我相信,看到这一点,没有人会感到惊讶: >>> n = 0x94 << 24 >>> n 2483027968L >>> hex(n) '0x94000000L' >>n=0x94>>n 248302796

我在windows上使用的是python 2.7、numpy 1.6.1和32位。我正在编写一个函数,将一些数据打包成32位整数,并从常量值生成C源声明。在这样做的过程中,我在numpy的uint8类型中发现了一些奇怪的行为

我相信,看到这一点,没有人会感到惊讶:

>>> n = 0x94 << 24
>>> n
2483027968L
>>> hex(n)
'0x94000000L'
>>n=0x94>>n
2483027968L
>>>十六进制(n)
“0x94000000L”
但对一个numpy uint8做同样的事情,你会得到一些让我惊讶的东西:

>>> n = np.uint8(0x94) << 24
>>> n
-1811939328
>>> hex(n)
'-0x6c000000'
>>>n=np.uint8(0x94)>>n
-1811939328
>>>十六进制(n)
“-0x6c000000”
有人会认为显式无符号类型返回负值的可能性更小

请注意,符号位为clear的值按预期工作:

>>> n = np.uint8(0x74) << 24
>>> n; hex(n)
1946157056
'0x74000000'
>>n=np.uint8(0x74)>>n;十六进制(n)
1946157056
“0x74000000”
我碰巧注意到numpy似乎正在将未签名类型升级为已签名类型:

>>> n = np.uint8(0x74) << 24
>>> type(n)
<type 'numpy.int32'>
>>n=np.uint8(0x74)>>类型(n)

这似乎是一个明显的错误。我找不到这样一个已知错误的引用,但是……是吗?

numpy
似乎将右侧参数(
24
)视为本机宽度的有符号整数(
int32
在您的情况下,在我的情况下,
int64

看起来
uint8
被提升为相同的类型,并且移位的结果也是相同的类型:

>>> np.uint8(0x94) << 56
-7782220156096217088
>>> type(np.uint8(0x94) << 56)
<type 'numpy.int64'>
>>> 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'