Simulating int arithmetic with wrap-around

Serhiy Storchaka storchaka at gmail.com
Fri Dec 30 10:14:00 EST 2016


On 30.12.16 16:47, Steve D'Aprano wrote:
> Again, assume both operands are in range for an N-bit signed integer. What's
> a good way to efficiently, or at least not too inefficiently, do the
> calculations in Python?

def to_unsigned(bits, x):
     return x & ((1<<bits)-1)

def to_signed(bits, x):
     offset = 1<<(bits-1)
     return to_unsigned(bits, x + offset) - offset




More information about the Python-list mailing list