Sugihara
Sugihara

Reputation: 1101

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)

Upvotes: 6

Views: 4961

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113930

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

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

Upvotes: 9

MatrixManAtYrService
MatrixManAtYrService

Reputation: 9131

If you'd prefer to do this generally and not just for 32 bits:

def truncate(value, bit_count):
    return value & (2**bit_count - 1)

This works because 2**bit_count -1 is all 1's in binary.

Upvotes: 2

Related Questions