Limit python calculations to 32-bit integers (signed 32bit int)

Python's ability to handle integers is very powerful, how powerful is it? Astronomical numbers can also be easily handled without overflow.

039aa53c60374cd78ad97a266cf11a2c.png

The figure above shows the result of Python's bit shift operation. Let's compare the result of the same calculation in the JavaScript environment:


f2b6f6de25354d27a0d8aa60b1b64704.png

If the integer type of JavaScript and C language is signed 32bit, its value range is -2147483648 ~ 2147483647. When learning this programming language before, I believe everyone wondered like me why there must be a wave of variable declarations before calculations? Shenma int, signed int, unsigned int, long int, later learning python programming and found that there is no need to declare variables, any variable name can be used at your fingertips, and the learning pressure has become easier. But now I suddenly find that sometimes we don't need Python to handle integers with so many digits, only 32-digit integers are enough. It is a pity that Python does not declare a 32-bit integer statement. In order to make the calculation result of Python the same as that of JavaScript and C, we have to use the c_int32() function of the ctypes library to process:

from ctypes import c_int32

def i32(n):
    # 如果n是负数就转换为32位对应的数
    if n < 0:
        n = (1 << 32) + n
    return c_int32(n).value

It can also be reduced to one line of code using lambda:

i32 = lambda x: c_int32(x).value if x >= 0 else c_int32((1 << 32) + x).value

operation result:

 

 

Guess you like

Origin blog.csdn.net/Scott0902/article/details/128980708