Simulating integer overflow in Python

前端 未结 5 1497
無奈伤痛
無奈伤痛 2020-12-06 18:04

Python 2 has two integer datatypes int and long, and automatically converts between them as necessary, especially in order to avoid integer overflo

5条回答
  •  甜味超标
    2020-12-06 18:46

    Use NumPy (which is written in C and exposes native machine-level integers). NumPy has these integer types:

    Signed integers:

    • np.int8
    • np.int16
    • np.int32

    Unsigned integers:

    • np.uint8
    • np.uint16
    • np.uint32

    For example (notice it overflows after integer value 127):

    import numpy as np
    
    counter = np.int8(0)
    one = np.int8(1)
    
    for i in range(130):
        print(type(counter), counter)
        counter = counter + one
    

    At any point you can convert back to a Python integer with just int(counter), for example.

提交回复
热议问题