Skip to content

Commit e1a30e4

Browse files
committed
Simplify readBitsIntBe() a bit
It's unnecessary to first left shift the mask to match the relevant bits of value stored in "bits", because after the mask is applied (`bits & mask`), this value will be shifted back right anyway. So it's easier to first shift "bits" to the right (and thus discard the least significant bits of it, which are no longer part of the value we want to read - but they remain in "bits" property for later fields, note that we don't reassign it while shifting) and then AND with the unchanged mask. It saves one useless operation and reduces cognitive load - this way is more straightforward.
1 parent 6f9fbf9 commit e1a30e4

File tree

1 file changed

+2
-4
lines changed

1 file changed

+2
-4
lines changed

src/main/java/io/kaitai/struct/KaitaiStream.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -207,11 +207,9 @@ public long readBitsIntBe(int n) {
207207

208208
// raw mask with required number of 1s, starting from lowest bit
209209
long mask = getMaskOnes(n);
210-
// shift mask to align with highest bits available in "bits"
210+
// shift "bits" to align the highest bits with the mask & derive the result
211211
int shiftBits = bitsLeft - n;
212-
mask <<= shiftBits;
213-
// derive reading result
214-
long res = (bits & mask) >>> shiftBits;
212+
long res = (bits >>> shiftBits) & mask;
215213
// clear top bits that we've just read => AND with 1s
216214
bitsLeft -= n;
217215
mask = getMaskOnes(bitsLeft);

0 commit comments

Comments
 (0)