Search code examples
pythonbit-manipulation

Python Truncating to 32-bit


How do I truncate my return value to 32-bits? I have the following code:

def rotate_left(value, shift):
    return hex((value << shift) | (value >> (32 - shift)))

I would like the return value to be

0x0000_000A instead of 0xA_0000_000A when calling rotate_right(0xA00_0000)


Solution

  • 0xFFFFFFFF is 32 bits so you can just do a logical or:

    result = number & 0xFFFFFFFF
    if result & (1 << 31):  # negative value
        result -= 1 << 32