views:

222

answers:

3

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.

A: 

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;
Tomas Petricek
Involving floating point numbers and a conversion to `int` probably doesn't qualify as “fastest” ...
Joey
Yes, I realized how to correct that just after I posted the initial version, but in the meantime, @doublep already posted that solution. I think I'll leave my version here as it explains the thought process that got me there :-).
Tomas Petricek
+5  A: 

Try this: (1 << X) - 1

doublep
It shouldn't, as long as you cast 1 to uint first (don't know C#, so dn't know how). Then it will be evaluated to 0 - 1, i.e. 32 1's on 32-bit machine.
doublep
You have the solution I was looking for. Straightforward and simple, without any loops. And when X equals the bit length of the integer, all bits become 1 as expected. It even works for the cornercase where X = 0. Thank you.
Virtlink
+2  A: 

Try this:

uint.MaxValue >> (32 - something)
SLaks