Reputation: 181
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?
Upvotes: 4
Views: 9898
Reputation: 2909
This is similar to shifting around, but uses multiplication and division:
255 // 16 * 16
Upvotes: 0
Reputation: 22089
number &= ~0xf
~
gives the binary inversion of the operand, so ~0xf
is equivalent to 0x...fff0
for any integer size.
Upvotes: 5
Reputation: 62369
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.
Upvotes: 3
Reputation:
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.
Upvotes: 0