Daniel A.A. Pelsmaeker
Daniel A.A. Pelsmaeker

Reputation: 50376

Fastest way to calculate an X-bit bitmask?

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.

Upvotes: 5

Views: 4351

Answers (3)

SLaks
SLaks

Reputation: 888263

Try this:

uint.MaxValue >> (32 - something)

Upvotes: 2

user319799
user319799

Reputation:

Try this: (1 << X) - 1

Upvotes: 6

Tomas Petricek
Tomas Petricek

Reputation: 243096

I think the following should work:

int mask = (int)Math.Pow(2, 31) - 1;

This is a single mathematical expression, but it isn't particularly efficient because calculating the power in this way is not really a good idea. However, since we're calculating a power of 2, we can do the same thing using shift:

int mask = (1 << 31) - 1;

Upvotes: 0

Related Questions