Bugfix: simplify the logic of extracting bit from a given byte
Change-Id: I0fbb9dae16f41deab2a302025eb0ba26afe2c6cf
diff --git a/utils/misc/src/main/java/org/onlab/util/ByteOperator.java b/utils/misc/src/main/java/org/onlab/util/ByteOperator.java
index 170b48c..4e7a6f5 100644
--- a/utils/misc/src/main/java/org/onlab/util/ByteOperator.java
+++ b/utils/misc/src/main/java/org/onlab/util/ByteOperator.java
@@ -40,8 +40,7 @@
return false;
}
- int bitMask = getHex((int) Math.pow(2, index));
- return (value & bitMask) == bitMask;
+ return (value & (0x1 << index)) != 0;
}
/**
@@ -54,14 +53,4 @@
public static byte toBit(boolean value, int bit) {
return (byte) (value ? bit : 0x00);
}
-
- /**
- * Convert decimal integer into hex integer.
- *
- * @param decimal decimal formatted integer
- * @return hex formatted integer
- */
- public static int getHex(int decimal) {
- return Integer.valueOf(String.valueOf(decimal), 16);
- }
}
diff --git a/utils/misc/src/test/java/org/onlab/util/ByteOperatorTest.java b/utils/misc/src/test/java/org/onlab/util/ByteOperatorTest.java
index 21dffbe..4fc994e 100644
--- a/utils/misc/src/test/java/org/onlab/util/ByteOperatorTest.java
+++ b/utils/misc/src/test/java/org/onlab/util/ByteOperatorTest.java
@@ -27,24 +27,12 @@
@Test
public void testGetBit() {
- byte eight = 0x08;
- assertThat(ByteOperator.getBit(eight, 0), is(false));
- assertThat(ByteOperator.getBit(eight, 1), is(false));
- assertThat(ByteOperator.getBit(eight, 2), is(false));
- assertThat(ByteOperator.getBit(eight, 3), is(true));
- assertThat(ByteOperator.getBit(eight, 4), is(false));
- assertThat(ByteOperator.getBit(eight, 5), is(false));
- assertThat(ByteOperator.getBit(eight, 6), is(false));
- assertThat(ByteOperator.getBit(eight, 7), is(false));
+ final byte[] number = new byte[] {1, 2, 4, 8, 16, 32, 64, -128};
- byte one = 0x01;
- assertThat(ByteOperator.getBit(one, 0), is(true));
- assertThat(ByteOperator.getBit(one, 1), is(false));
- assertThat(ByteOperator.getBit(one, 2), is(false));
- assertThat(ByteOperator.getBit(one, 3), is(false));
- assertThat(ByteOperator.getBit(one, 4), is(false));
- assertThat(ByteOperator.getBit(one, 5), is(false));
- assertThat(ByteOperator.getBit(one, 6), is(false));
- assertThat(ByteOperator.getBit(one, 7), is(false));
+ for (int i = 0; i < number.length; i++) {
+ for (int j = 0; j < 8; j++) {
+ assertThat(ByteOperator.getBit(number[i], j), is(i == j));
+ }
+ }
}
}