简体   繁体   English

按位移位在 Python 中返回意外值

[英]Bitwise shift returns unexpected value in Python

I'm performing 55 << 30 in C# and Python 3. C# returns -1073741824 , which is what I want, but Python returns 59055800320 . I'm performing 55 << 30 in C# and Python 3. C# returns -1073741824 , which is what I want, but Python returns 59055800320 . Can someone explain why exactly this happens, and what I can do to fix it?有人可以解释为什么会发生这种情况,以及我能做些什么来解决它?

python ints are arbitrarily large... you can force it sort of python 整数任意大......你可以强制它排序

import numpy

numpy.int32(55) << 30

Python integers are unbounded, so 59055800320 is the correct answer, but to simulate C#'s 32-bit limitation on integers and 2s complement negative numbers, you can do the math: Python 整数是无界的,因此59055800320是正确答案,但要模拟 C# 对整数和 2s 补码负数的 32 位限制,您可以进行数学运算:

>>> hex(55)
'0x37'
>>> hex(55 << 30)  # 36-bit result, too large for 32-bit integers
'0xdc0000000'
>>> hex(55 << 30 & 0xffffffff) # mask off lower 32 bits.
'0xc0000000'
>>> ((55 << 30) & 0xffffffff)  # but the sign (bit 31) is a one, so it should be negative
3221225472

Bit 31 in a 32-bit signed integer has value -2 31 , but unsigned it has value 2 31 , meaning the value is 2 32 too high, so: 32 位有符号 integer 中的位 31 的值为 -2 31 ,但无符号的值为 2 31 ,这意味着该值 2 32太高了,所以:

>>> ((55 << 30) & 0xffffffff) - (1<<32)
-1073741824

Here's a function:这是一个 function:

def signed_32bit_shift_left(n,s):
    tmp = (n << s) & 0xffffffff
    return tmp - (1<<32) if tmp & 0x80000000 else tmp

As the others have said, Python int s are much larger than you might expect.正如其他人所说, Python int比您预期的要大得多。 To observe this (Python 3.7.4):要观察这一点(Python 3.7.4):

>>> import sys
>>> type(55)
<class 'int'>
>>> sys.getsizeof(int())
24

sys.getsizeof() will return the size, in bytes, of an object in memory. sys.getsizeof()将返回 memory 中 object 的大小(以字节为单位)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM