devoured elysium
devoured elysium

Reputation: 105037

BitSet shows up values backward?

I've set up the following code running with Java:

BitSet bitSet = BitSet.valueOf(new byte[] { (byte)15 });
System.out.println(bitSet);

which to my surprise prints

{0, 1, 2, 3} //the indexes of the 1's in the bitset

instead of

{ 4, 5, 6, 7 }.

15 in 2's complement is written as 00001111 (with 1 byte), if I am not mistaken.

That makes me wonder why would a BitSet show the indexes backward. Is there any rational explanation?

Upvotes: 4

Views: 277

Answers (1)

Borealid
Borealid

Reputation: 98459

Quoting from the Java standard for BitSet:

Returns a string representation of this bit set. For every index for which this BitSet contains a bit in the set state, the decimal representation of that index is included in the result. Such indices are listed in order from lowest to highest, separated by ", " (a comma and a space) and surrounded by braces, resulting in the usual mathematical notation for a set of integers.

As this says, the order is "from lowest to highest". This means the least significant bit (the ones bit) first, and the most significant bit last.

Either ordering (notational order left-to-right or numeric order least-to-most) would make sense, albeit in a different way.

Upvotes: 5

Related Questions