Fastest way to calculate an X-bit bitmask?
Posted
by Virtlink
on Stack Overflow
See other posts from Stack Overflow
or by Virtlink
Published on 2010-04-18T23:31:40Z
Indexed on
2010/04/18
23:43 UTC
Read the original article
Hit count: 492
I have been trying to solve this problem for a while, but couldn't with just integer arithmetic and bitwise operators. However, I think its possible and it should be fairly easy. What am I missing?
The problem: to get an integer value of arbitrary length (this is not relevant to the problem) with it's X least significant bits sets to 1 and the rest to 0. For example, given the number 31, I need to get an integer value which equals 0x7FFFFFFF (31 least significant bits are 1 and the rest zeros).
Of course, using a loop OR-ing a shifted 1 to an integer X times will do the job. But that's not the solution I'm looking for. It should be more in the direction of (X << Y - 1)
, thus using no loops.
© Stack Overflow or respective owner