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)
Truncation Using Casting If our double value is within the int range, we can cast it to an int. The cast truncates the decimal part, meaning that it cuts it off without doing any rounding.
The truncate() method resizes the file to the given number of bytes. If the size is not specified, the current position will be used.
0xFFFFFFFF
is 32 bits so you can just do a logical or:
result = number & 0xFFFFFFFF
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With