Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 484
Sugihara Avatar asked Nov 06 '14 04:11

Sugihara


People also ask

Does casting truncate?

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.

What is truncation in Python?

The truncate() method resizes the file to the given number of bytes. If the size is not specified, the current position will be used.


2 Answers

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

result = number & 0xFFFFFFFF
like image 182
Joran Beasley Avatar answered Oct 17 '22 04:10

Joran Beasley


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.

like image 1
MatrixManAtYrService Avatar answered Oct 17 '22 04:10

MatrixManAtYrService