0

So I'm getting an unsigned int passed into my function. Now I must obtain the n LSB bits of that integer and use it to access a location in an array of size 2^n.

So for example, if my array is of size 1024, n = 10.

I am currently doing this:

unsigned int location = my_unsigned_int << n;

However this doesn't work as location ends up being way too large and out of bounds.

Alk
  • 5,215
  • 8
  • 47
  • 116

1 Answers1

3

You can just mask the bits you want:

unsigned int location = my_unsigned_int & ((1<<n) - 1);

This assumes that your int is at least n+1 bits in size.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101