123
123

Reputation: 5824

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

Upvotes: 6

Views: 13035

Answers (6)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215447

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.

Upvotes: 1

James
James

Reputation: 9278

To take another path you can try

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

Upvotes: 4

Jesse Cohen
Jesse Cohen

Reputation: 4040

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

x &= mask;

Upvotes: 1

Matteo Italia
Matteo Italia

Reputation: 126867

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

Upvotes: 1

Joe
Joe

Reputation: 42646

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

Upvotes: 2

templatetypedef
templatetypedef

Reputation: 372992

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!

Upvotes: 15

Related Questions