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:
JavaScript
x
2
1
number &= 0xfffffff0
2
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
JavaScript
1
2
1
number &= ~0xf
2
~
gives the binary inversion of the operand, so ~0xf
is equivalent to 0x...fff0
for any integer size.