'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?



Solution 1:[1]

Language-agnostic answer, as this is really more about masking operations in general. To mask out the lowest four bits of in integer, start with this:

mask = 2^4 - 1

(alternatively, 0xf, or 15, or whatever - showing it that way to make it a bit more clear how you might change it for different lengths you want to mask out...)

Then, extract the lowest 4 bits of your variable:

lowbits = value & mask

Then, clear those bits in your variable:

value = value ^ lowbits

^ here represents exclusive-or (xor).

This procedure should work in any language (provided it has the required bit operations), and regardless of the integer bit size.

Solution 2:[2]

There is nothing wrong with or "kludgy" about using a 64-bit mask if the number might be up to 64 bits.

Taking the number of bits as a parameter to the function would be a poor choice. Why ask for something to be specified when it is not needed? It would only create an opportunity for mistakes to be made.

Solution 3:[3]

This is similar to shifting around, but uses multiplication and division:

255 // 16 * 16

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 twalberg
Solution 2
Solution 3 user1277476