简体   繁体   中英

Clear lower 16 bits

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

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!

要采取另一条路,你可以尝试

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

一种方法是按位AND与0xFFFF0000,例如value = value & 0xFFFF0000

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
int x = 0x12345678;
int mask = 0xffff0000;

x &= mask;

Assuming the value you want to clear bits from has an unsigned type not of "small rank", this is the safest, most portable way to clear the lower 16 bits:

b &= -0x10000;

The value -0x10000 will be promoted to the type of b (an unsigned type) by modular arithmetic, resulting in all high bits being set and the low 16 bits being zero.

Edit: Actually James' answer is the safest (broadest use cases) of all, but the way his answer and mine generalize to other similar problems is a bit different and mine may be more applicable in related problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM