Reputation: 23
I am currently trying to read a single bit from a File in Java.
I read the Data into a byte array and then convert the byte array into a Bitset.
The Problem is that sometimes there are a few bits missing in the converted Bitset.
In the following Example i have 2 Byte Arrays, each with 25 very similar Bytes. But one is converted into the expected 200 bits and the other one into only 197 bits and i have no idea why.
import java.nio.ByteBuffer;
import java.util.BitSet;
public class Main {
public static void main(String[] args) {
ByteBuffer cb = ByteBuffer.wrap(new byte[] {(byte)0x18,(byte)0x8C,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,});
BitSet cBits = BitSet.valueOf(cb);
System.out.println(cBits.length());
ByteBuffer db = ByteBuffer.wrap(new byte[] {(byte)0x17,(byte)0x8c,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x18,(byte)0x8c,(byte)0x8c,});
BitSet dBits = BitSet.valueOf(db);
System.out.println(dBits.length());
}
}
Upvotes: 2
Views: 131
Reputation: 41271
The length() of a Java bitset is a consequence of the most significant set bit, not the length of the array which was passed. This is consistent with the bitset's description as a data structure which grows as needed--its logical size is a consequence of its set bits, not the physical capacity of some underlying buffer.
Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits.
Your first example has the most significant byte as 0x18, or binary 00011000. The three leading zero bits account for the discrepancy when compared with the second bitset, whose most significant byte is 0x8c (10001100)
Upvotes: 2