Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 222
123 Avatar asked Jul 29 '11 00:07

123


1 Answers

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!

like image 193
templatetypedef Avatar answered Oct 06 '22 01:10

templatetypedef