Generating bitmasks

Hey all.

I want to guarantee that an input (size_t value) has all bits greater than the first count bits cleared.

My first thought was to simply mask it thusly:

    value &= (1U << count) - 1; oops! edited to use &= ... it was late...

However, it occurred to me this might not work on some architectures, particularly if count is equal to the maximum number of bits available in value.

I have currently coded it as:

1
2
value <<= (sizeof( value ) * 8) - count;
value >>= (sizeof( value ) * 8) - count;

But I am not too pleased with this solution (it is ugly).

The next thought is simply to put a test on the first version, so that the masking operation only happens if needed:

1
2
if (count < (sizeof( value ) * 8))
  value &= (1U << count) - 1;

While I like this version better, the former is probably faster, and the code must be fast...

(Perhaps it is just too late for me right now...)

Any thoughts on foreign architectures with shift and binary number representations different than the usual fare (x86 and MIPS systems)?

Thank you for your time.
Last edited on
value &= (1U << count) - 1; // I assume you meant &= instead of |=

I don't see why you can't just use this one. I can't think of a single architecture where this wouldn't work, as long as the architecture supports unsigned types (are there any that don't?) 0U - 1 == 0xFFFFFFFFF... on any architecture, right?

EDIT:
As long as sizeof(1U << count) >= sizeof(value)
Last edited on
Well, if count >= sizeof(value)*8, then the function has to return true, since all bits greater than the most significant bit will be cleared.
0U - 1 == 0xFFFFF...
Hmm... unsigned value... yes, it should...
I suppose this is what happens when my brain stops functioning...


Thank you both. Yes, count is checked for proper domain.
Topic archived. No new replies allowed.