Clear lower 16 bits

11,189

Solution 1

To clear any particular set of bits, you can use bitwise AND with the complement of a number that has 1s in those places. In your case, since the number 0xFFFF has its lower 16 bits set, you can AND with its complement:

b &= ~0xFFFF; // Clear lower 16 bits.

If you wanted to set those bits, you could instead use a bitwise OR with a number that has those bits set:

b |= 0xFFFF; // Set lower 16 bits.

And, if you wanted to flip those bits, you could use a bitwise XOR with a number that has those bits set:

b ^= 0xFFFF; // Flip lower 16 bits.

Hope this helps!

Solution 2

To take another path you can try

x = ((x >> 16) << 16);

Solution 3

One way would be to bitwise AND it with 0xFFFF0000 e.g. value = value & 0xFFFF0000

Solution 4

Use an and (&) with a mask that is made of the top 16 bit all ones (that will leave the top bits as they are) and the bottom bits all zeros (that will kill the bottom bits of the number).

So it'll be

0x12345678 & 0xffff0000

If the size of the type isn't known and you want to mask out only the lower 16 bits you can also build the mask in another way: use a mask that would let pass only the lower 16 bits

0xffff

and invert it with the bitwise not (~), so it will become a mask that kills only the lower 16 bits:

0x12345678 & ~0xffff

Solution 5

int x = 0x12345678;
int mask = 0xffff0000;

x &= mask;
Share:
11,189
123
Author by

123

please delete me

Updated on June 04, 2022

Comments

  • 123
    123 almost 2 years

    I'm not so good with bitwise operators so please excuse the question but how would I clear the lower 16 bits of a 32-bit integer in C/C++?

    For example I have an integer: 0x12345678 and I want to make that: 0x12340000

  • Ray Toal
    Ray Toal over 12 years
    This is actually nice because it works with 16 and 64-bit values also, if I'm not mistaken.
  • templatetypedef
    templatetypedef over 12 years
    @James- If you try doing something like b & 0xFFFF0000 on a non-32 bit machine (for example, a 64-bit machine), then this might accidentally end up clearing the high 32 bits in addition to the low 32 bits.
  • R.. GitHub STOP HELPING ICE
    R.. GitHub STOP HELPING ICE over 12 years
    It does not work with 64-bit values. 0xffff has type int which is almost surely 32-bit in real-world systems even if b has type unsigned long or such. Also, ~0xffff has implementation-defined behavior since 0xffff has signed type. See my answer for a better approach.
  • Jens Gustedt
    Jens Gustedt over 12 years
    Why not doing something like b &= ~(1 ? 0xFFFF : b); ?
  • Akshay Mathur
    Akshay Mathur over 6 years
    Can you please tell what if 0x12345678 and I want to make that: 0x00005678, or should I open another question ?