5YrsLaterDBA 5YrsLaterDBA - 20 days ago 5
Java Question

retrieve value stored in certain bits of an int

We divided an int to save three values into it. For example the first 8 bits (from left to right) hold one value, the 8th to 12th bits hold another value and rest of bits hold the third value.

I am writing a utility method to get value from a certain range of bits of an int. is it good enough? do you have a better solution? The startBitPos and endBitPos are count from right to left.

public static int bitsValue(int intNum, int startBitPos, int endBitPos)
{
//parameters checking ignored for now
int tempValue = intNum << endBitPos;
return tempValue >> (startBitPos + endBitPos);
}


EDIT:

I am sure all values will be unsign.

Answer

No, this isn't quite right at the moment:

  • You should use the unsigned right shift operator to avoid ending up with negative numbers when you don't want them. (That's assuming the original values are unsigned, of course.)
  • You're not shifting left by the appropriate amount to clear the extraneous high bits.

I suspect you want:

// Clear unnecessary high bits
int tempValue = intNum << (31 - endBitPos);
// Shift back to the lowest bits
return tempValue >>> (31 - endBitPos + startBitPos);

Personally I'd feel more comfortable with a mask-and-shift than this double shifting, but I'm finding it hard to come up with something as short as the above.