Java gets a range of bits from long

I need to extract certain bit ranges with a long value, for example:

long input = 15367 (11110000000111) 

What I need to do is extract two long values ​​from the original long,

 First long is 5 bits starting from bit 0, so bits 0:4 = 7 (0111) Second long is 56 bits starting from bit 8, so bits 7:55 = 60 (1111000) 

I know that this can be done using bit shifting and masking, however, I'm not quite sure how to implement this so that it is dynamic every time, since every time I need to do this, the long ones will be different, and therefore will also be specific bit ranges.

I read about BitSets and BitArrays, however I'm not quite sure if these are the right things to work.

Any advice on the best way to implement it is welcome.

Thanks!

+7
java binary logical-operators bitmask
source share
2 answers

To extract the nrBits bits starting at 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; } 

Pay attention to the user of the shift operator >>> ; this means that you are not wearing a sign bit.

As for (1L << nrBits) - 1L , i.e. 2^nrBits - 1 . L must have long constants.

Also note that there is no “boundary check” (for example, offset or number of bits greater than 63 or negative).

+8
source share

To extract the bits between bit x and bit y, where x is the larger of the two numbers, you could say

 long mask = (Math.pow(2,x+1)-1)- (Math.pow(2,y+1)-1); long extract = input & mask; 
+2
source share

All Articles