Skip to content
Advertisement

How To Mask Out Lower ‘x’ Bits of Python Integer Of Unknown Size

I am looking for a way to mask out (set to ‘0’) the lowest four bits of an integer in Python when I don’t know the total length of the number. If I knew the length of the integer beforehand I could just set the rest of the mask to 0xff, for instance if the integer would always be 32 bits long I could use:

number &= 0xfffffff0     

But if I tried to use a 64-bit number there then it would mask out bits 32-63. The two things I thought of were to make the mask really long (e.g. 0xffffffffffffffffff0) or to take the number of bits as a parameter to the function. Both would probably work well enough but they seem kludgy. Is there a better/more Pythonic way to do this?

Advertisement

Answer

number &= ~0xf

~ gives the binary inversion of the operand, so ~0xf is equivalent to 0x...fff0 for any integer size.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement