5

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.

Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157

3 Answers3

6

Try this: (1 << X) - 1

  • 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. –  Apr 18 '10 at 23:43
  • 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. – Daniel A.A. Pelsmaeker Apr 19 '10 at 00:05
2

Try this:

uint.MaxValue >> (32 - something)
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

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
  • 240,744
  • 19
  • 378
  • 553
  • Involving floating point numbers and a conversion to `int` probably doesn't qualify as “fastest” ... – Joey Apr 18 '10 at 23:38
  • 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 Apr 18 '10 at 23:39