graille
graille

Reputation: 1231

Simulate integer overflow in Python

I'm working with Python and I would like to simulate the effect of a C/C++ cast on an integer value.

For example, if I have the unsigned number 234 on 8 bits, I would like a formula to convert it to -22 (signed cast), and another function to convert -22 to 234 (unsigned cast).

I know numpy already has functions to do this, but I would like to avoid it.

Upvotes: 1

Views: 562

Answers (2)

Alain T.
Alain T.

Reputation: 42133

You could use bitwise operations based on a 2^(n-1) mask value (for the sign bit):

size   = 8
sign   = 1 << size-1

number   = 234
signed   = (number & sign-1) - (number & sign)
unsigned = (signed & sign-1) | (signed & sign)

print(signed)   # -22
print(unsigned) # 234

Upvotes: 3

Joni
Joni

Reputation: 111219

You can easily create such a function yourself:

def toInt8(value):
    valueUint8 = value & 255
    if valueUint8 & 128:
       return valueUint8 - 256
    return valueUint8

>>> toInt8(234)
-22

You can make a version that accepts the number of bits as a parameter, rather than it being hardcoded to 8:

def toSignedInt(value, bits):
    valueUint8 = value & (2**bits - 1)
    if valueUint8 & 2**(bits-1):
       return valueUint8 - 2**bits
    return valueUint8

>>> toSignedInt(234, 8)
-22

Upvotes: 2

Related Questions