I'm working mostly with low level programming, where the size of the variables are limited the variable type/register size.
Let's say I would like to do several bit level operations with Python and I need to make sure that the upper bits of the currently executed instruction has no impact to the upcoming one.
Is there any trick to limit the size of the variable in Python w/o using additional long binary masks or performance wasting libraries?
In the sample code I limited the value of
x to 32 bits with the
def reflect_bits(x): x = (((x & 0x55555555) << 1) | ((x >> 1) & 0x55555555)) & 0xFFFFFFFF x = (((x & 0x33333333) << 2) | ((x >> 2) & 0x33333333)) & 0xFFFFFFFF x = (((x & 0x0F0F0F0F) << 4) | ((x >> 4) & 0x0F0F0F0F)) & 0xFFFFFFFF x = ((x << 24) | ((x & 0xFF00) << 8) | ((x >> 8) & 0xFF00) | (x >> 24)) & 0xFFFFFFFF return x
User contributions licensed under CC BY-SA 3.0