To extract nrBits
bits starting from offset offset
, you can do:
public static long extractSub(final long l, final int nrBits, final int offset)
{
final long rightShifted = l >>> offset;
final long mask = (1L << nrBits) - 1L;
return rightShifted & mask;
}
Note the user of the >>>
right shift operator; this is so you don't carry the sign bit around.
As to (1L << nrBits) - 1L
, that is 2^nrBits - 1
. The L
is to have long
constants.
Also note that there is no "bounds checking" (for instance, an offset or number of bits greater than 63 or negative).