Skip to content

Commit 2208aad

Browse files
committed
Fix Bytes.bitAt to respect byte order
Closes #39. bitAt now checks byte order before locating the desired bit.
1 parent c2ef5bd commit 2208aad

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

src/main/java/at/favre/lib/bytes/Bytes.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1338,7 +1338,11 @@ public boolean endsWith(byte[] subArray) {
13381338
*/
13391339
public boolean bitAt(int bitIndex) {
13401340
Util.Validation.checkIndexBounds(lengthBit(), bitIndex, 1, "bit");
1341-
return ((byteAt(length() - 1 - (bitIndex / 8)) >>> bitIndex % 8) & 1) != 0;
1341+
if (byteOrder == ByteOrder.BIG_ENDIAN) {
1342+
return ((byteAt(length() - 1 - (bitIndex / 8)) >>> bitIndex % 8) & 1) != 0;
1343+
} else {
1344+
return ((byteAt(bitIndex / 8) >>> bitIndex % 8) & 1) != 0;
1345+
}
13421346
}
13431347

13441348
/**

src/test/java/at/favre/lib/bytes/BytesMiscTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,12 @@ public void bitAt() {
272272
fail();
273273
} catch (IndexOutOfBoundsException ignored) {
274274
}
275+
276+
Bytes bytes = Bytes.wrap(new byte[]{1, 0, 2, 0}).byteOrder(ByteOrder.LITTLE_ENDIAN);
277+
assertTrue(bytes.bitAt(0));
278+
assertTrue(bytes.bitAt(17));
279+
assertFalse(bytes.bitAt(8));
280+
assertFalse(bytes.bitAt(31));
275281
}
276282

277283
@Test

0 commit comments

Comments
 (0)