Clear lower 16 bits

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

For example, I have an integer: 0x12345678, and I want to do this: 0x12340000

+6
source share
6 answers

To clear any specific set of bits, you can use bitwise AND with the addition of a number having 1 in these places. In your case, since the number 0xFFFF has its lower 16 bits, you can AND with its addition:

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

If you want to set these bits, instead you can use a bitwise OR with the number in which these bits are set:

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

And if you want to flip these bits, you can use the bitwise XOR with the number in which these bits are set:

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

Hope this helps!

+13
source

To choose a different path, you can try

 x = ((x >> 16) << 16); 
+4
source

One way is bitwise AND with 0xFFFF0000, for example. value = value & 0xFFFF0000

+2
source

Use a and ( & ) with a mask consisting of the upper 16 bits of all (which will leave the upper bits as they are), and the lower bits - all zeros (which will kill the lower bits of the number).

So it will be

 0x12345678 & 0xffff0000 

If the type size is unknown and you want to mask only the lower 16 bits, you can also create a mask in a different way: use a mask that skips only the lower 16 bits

 0xffff 

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

 0x12345678 & ~0xffff 
+1
source
 int x = 0x12345678; int mask = 0xffff0000; x &= mask; 
+1
source

Assuming that the value you want to clear the bits is of an unsigned type and not a "low rank", this is the safest and most portable way to clear the lower 16 bits:

 b &= -0x10000; 

The value -0x10000 will be assigned to type b (unsigned type) using modular arithmetic, as a result of which all high bits will be set, and the lower 16 bits will be zero.

Edit: Actually, James's answer is the safest (the widest possible use cases) for everyone, but the way his answer and mine generalize to other similar problems is slightly different, and mine may be more applicable in related problems.

+1
source

Source: https://habr.com/ru/post/893833/


All Articles