I have a bitmask (stored as a short). For various purposes, I want to zero out all but the last 5 bits - I'm sure there is an easy to way to do this via bitwise operators, but it eludes me.
1010 01101 1011 0111 -> 0000 0000 0001 0111
Thanks
I have a bitmask (stored as a short). For various purposes, I want to zero out all but the last 5 bits - I'm sure there is an easy to way to do this via bitwise operators, but it eludes me.
1010 01101 1011 0111 -> 0000 0000 0001 0111
Thanks
Use something like:
x & 0x1f
In binary, your example would be:
1010 1101 1011 0111
& 0000 0000 0001 1111
---------------------
0000 0000 0001 0111
When using the &
operator, 0 bits in the mask result in 0 bits in the result. 1 bits in the mask copy the corresponding bits to the result.
Value = OriginalValue & 0x1F
Something like this:
your_variable_name & ((1 << 5) - 1)
(1 << 5) - 1 will give you a 11111, and then you and it with your value.