1

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.