last 5 bits of a bitmask

c#

Solution

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.

Problem

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

Original source

Related problems