The two alternatives you put up for 4.
are effectively the same :)
The trick is that this produces a string of binary 1
s, up to the given numberOfBits
- ie. (1 << 3) - 1
produces 7
, or 111
in binary - in other words, "give me only the numberOfBits
least significant bits".
Basically, you've described this well, if overly wordy.
The result of the first line is a sequence of numberOfBits
bits. The value is a xor between the bit sequences starting from the two different indices and numberOfBits
long. The and
then simply discards the bits higher than numberOfBits
.
The second line then exploits the fact that a ^ b ^ a == b
, and b ^ a ^ b == a
, and the order of operations doesn't matter - the xor operation is commutative.
As long as the two sequences don't overlap and don't cross the decimal point, it should work just fine :)