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.