Consider following code (java8):
@Test
public void testBigIntegerVsBitSet() throws Throwable
{
String bitString529 = "00000010 00010001"; // <- value = 529 (LittleEndian)
byte[] arr529 = new byte[] { 0x02, 0x11 }; // <- the same as byte array (LittleEndian)
BigInteger bigIntByString = new BigInteger( bitString529.replace( " ", ""), 2); // throws if there is a blank!
BigInteger bigIntByArr = new BigInteger( arr529);
BitSet bitsetByArr = BitSet.valueOf( arr529); // interpretes bit-order as LittleEndian, but byte-order as BigEndian !!!
System.out.println( "bitString529 : " + bitString529); // bitString529 : 00000010 00010001
System.out.println( "arr529.toString : " + Arrays.toString( arr529)); // arr529.toString : [2, 17]
System.out.println( "bigIntByString : " + bigIntByString); // bigIntByString : 529
System.out.println( "bigIntByArr : " + bigIntByArr); // bigIntByArr : 529
System.out.println( "bitsetByArr : " + bitsetByArr.toString() ); // bitsetByArr : {1, 8, 12}
System.out.println( "expecting : {0, 4, 9}"); // expecting : {0, 4, 9}
String bigIntByStringStr = toBitString( bigIntByString::testBit);
String bigIntByArrStr = toBitString( bigIntByArr::testBit);
String bitsetByArrStr = toBitString( bitsetByArr::get);
System.out.println( "bigIntByStringStr: " + bigIntByStringStr); // bigIntByStringStr: 1000100001000000
System.out.println( "bigIntByArrStr : " + bigIntByArrStr); // bigIntByArrStr : 1000100001000000
System.out.println( "bitsetByArrStr : " + bitsetByArrStr ); // bitsetByArrStr : 0100000010001000
}
private String toBitString( Function<Integer, Boolean> aBitTester)
{
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < 16; i++ )
{
sb.append( aBitTester.apply( i) ? "1" : "0");
}
return sb.toString();
}
which prooves that the BitSet parses byte arrays as BIG_ENDIAN whereas it interpretes the bit order (of a single byte) as LITTLE_ENDIAN. The BigInteger in contrast interpretes both in LITTLE_ENDIAN, even when loaded by a bit string.
Especially the iteration on the bit indices of the two classes (BitInteger::testBit vs. BitSet::get) delivers different results.
Is there a reason for this inconsistency?