I’m working on a small java project aiming to transform a BitSet into several BitSets and then those into several arrays of Bytes:
For example, I wish to split up in two parts a BitSet and convert each part into an int :
byte[] bytesToBeConverted = {(byte)0x05, (byte)0x00};
BitSet bitSetToBeConverted = BitSet.valueOf(bytesToBeConverted);
BitSet BitSetPart1 =new BitSet(8);
BitSetPart1=bitSetToBeConverted.get(0,8);
int intPart1 = (int)(BitSetPart1.toByteArray()[0]); //intPart1 ==5
BitSet BitSetPart2 =new BitSet(8);
BitSetPart2 = bitSetToBeConverted.get(8,16);
int intPart2 = (int)(BitSetPart2.toByteArray()[0]); //intPart2 == 0 is wanted
Whereas no problem does occur in the first part (converting bitSetPart1 into intPart1), the second part, where BitSetpart2 has to be initialized with false, causes an exception to be raised when accessing to the result of the method toByteArray() :java.lang.ArrayIndexOutOfBoundsException
toByteArray seems to return null in that case.
Does that mean that a zero is a forbiden value for that type of operations?
In that case would you rather extend the BitSet Class and Override the toByteArray() method?
or create a class completely separated from the BitSet with an extra method to overcome that problem?
or is there another way to perform that kind of operation that I haven’t mentionned?
Thanks a lot for your answers!
From the Javadoc of
toByteArray():and from the Javadoc of
length():Since the second
BitSetcontains no set bits, it returns an array of length zero, as the Javadoc clearly specifies.If you want to pad the result of
toByteArray()out to a specified number of bytes, then useArrays.copyOf(bitSet.toByteArray(), desiredLength).