Skip to content

Commit 5e2bdb8

Browse files
authored
Merge pull request #40 from gfpeltier/master
Fix Bytes.bitAt to respect byte order
2 parents c2ef5bd + 2208aad commit 5e2bdb8

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)