2

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

Prescott
  • 7,312
  • 5
  • 49
  • 70

3 Answers3

9

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Since type very well could be stored in PDP-Endian I am down voting for not giving advice to perform binary operations according to endianess although it might involve common sense. Although you did give a binary example you could have also shown and told the obvious. – Jay May 30 '12 at 02:02
  • @Jay: Bitwise logical operations are independent of endianness. Endianness only makes a difference when values are stored in memory - once they are loaded into CPU registers, there is no difference. Your objection is specious. – Greg Hewgill May 30 '12 at 02:09
  • As I stated below... his example is loaded into memory so... 'The latter may be true but your example is shifting from loaded memory hence the address of notation used ;P' – Jay May 30 '12 at 03:33
1

Value = OriginalValue & 0x1F

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39
-1

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.

MK.
  • 33,605
  • 18
  • 74
  • 111
  • yeah also the operator precedence was messed up. fixed both. – MK. May 29 '12 at 22:21
  • @Jay: no it wouldn't. Not in this case. – Borodin May 29 '12 at 22:32
  • Well being as var is not valid in C I assumed that a auto conversion was happening and that the size of the pointer was not the size of the int for a weird reason but I could also just remove my comment :p None the less thanks for pointing it out – Jay May 29 '12 at 22:35
  • @Jay var was supposed to be just a generic variable name. I forgot that it might be a reserved word. – MK. May 30 '12 at 00:44
  • @jay sir, you are insane. Bit shift operators take big/little endinan into account. – MK. May 30 '12 at 02:48
  • 2
    @Jay finding a good explanation was surprisingly difficult, but here it is: http://stackoverflow.com/a/1041573/68105 – MK. May 30 '12 at 03:03
  • The latter may be true but your example is shifting from loaded memory hence the address of notation used ;P And thank you for the compliment... I up voted your reply! – Jay May 30 '12 at 03:31
  • @Jay shifting from loaded memory? Address of notation? I don't follow. – MK. May 30 '12 at 04:16
  • Shifting was the wrong term, I meant applying a binary operation to... and I can't argument anymore for 2 reasons... 1 I am high and 2 I am tired :p – Jay May 30 '12 at 04:34