user2057841
user2057841

Reputation: 213

How to zero out bottom n bits in a C unsigned int?

I am trying to write my own C floor function. I am stuck on this code detail. I would just like to know how I can zero out the bottom n bits of an unsigned int.

For example, to round 51.5 to 51.0, I need to zero out the bottom 18 bits, and keep the top 14. Since it's a floor function, I want to make a mask to zero out the bottom (23 minus exponent) bits from the float representation. I know how to make a mask for individual cases like that, but I'm not sure how to code it so that it will work for all. Please help.

Upvotes: 1

Views: 4986

Answers (2)

aaaaaa123456789
aaaaaa123456789

Reputation: 5842

A much simpler way is doing just this:

value = (value >> bits) << bits

because the shift left will fill it in with zeroes, not whatever was in there.

Upvotes: 12

Jerry Coffin
Jerry Coffin

Reputation: 490048

Shift a number left N bits. Subtract one. Invert the bits. And with the number you need to mask.

1 << 14 = 00000000000000000010000000000000
     -1 = 00000000000000000001111111111111
     ~  = 11111111111111111110000000000000

When you and with this, a 1 in the mask will preserve the input, and 0 in the mask will set the result to 0.

Upvotes: 3

Related Questions