1

[edit] Please close/delete, I was just counting from the wrong side.

I'm working with this function with the hopes of extracting some number of bits from a starting position in a value.

// Extract K bits from position P in the value
int getBits(int value, int k, int p)
{
   return (((1 << k) - 1) & (value >> (p - 1)));
}

When I test it with the int 2303 (0000100011111111) I get an output of 15.

printf("%d\n", getBits(2303,4,4));

I'm trying to grab the 4 bits starting at position 4 to make it print out 8. Where am I going wrong?

Crizly
  • 971
  • 1
  • 12
  • 33

2 Answers2

3

The four bits at position 4 (what most people would call "bit 3") of your number are 1111, so you're getting the expected output:

0000100011111111
         ^^^^ these ones

It looks like you wanted:

getBits(2303, 4, 9)
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
2

The position parameter starts from the least significant bit. In other words, count from the right, not the left.

OregonJim
  • 326
  • 2
  • 10