Search code examples
javabitset

Understanding the implementation of Java BitSet class


BitSet object provides somewhat unclear results when I tried to test it and make sense of it.

main:

byte f = (byte)0b00101000;
byte s = (byte)0b11111111;
byte[] bytes = new byte[]{f, s};
BitSet bs = BitSet.valueOf(bytes);

printlnLog("Input bitset: " + bs);
printlnLog("Input bitset length: " + bs.size());

Output:

Input bitset: {3, 5, 8, 9, 10, 11, 12, 13, 14, 15}
Input bitset length: 64

Output makes no sense for me. I do not understand the underlying logic of BitSet. I will appreciate your help!


Solution

  • Is this clear enough?

    byte f = (byte)0b00101000;
    // Bits 0 to 7   --5-3---                  
    byte s = (byte)0b11111111;
    // Bits 8 to 15  54321098
    byte[] bytes = new byte[]{f, s};
    BitSet bs = BitSet.valueOf(bytes);
    

    And the 64 is due to the number of bits currently allocated. The maximum bit number of set bits can be obtained by calling bs.length().

    There is nothing to indicate the trailing unset bits defined by any constructor or method, but this isn't necessary. This doesn't hurt since you aren't punished by using an index (e.g. in BitSet.get(int index)) with a value beyond this or that "end" of a BitSet.