Kate_Bush
Kate_Bush

Reputation: 33

How do I convert a bitSet initialized with false in a byte containing 0 in java

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!

Upvotes: 3

Views: 1450

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198093

From the Javadoc of toByteArray():

More precisely, if

byte[] bytes = s.toByteArray(); 

then

bytes.length == (s.length()+7)/8

and from the Javadoc of length():

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.

Since the second BitSet contains 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 use Arrays.copyOf(bitSet.toByteArray(), desiredLength).

Upvotes: 3

alf
alf

Reputation: 8513

The empty bitset returns an empty array, hence getting [0] is indeed illegal.

Try

BitSetPart2 = bitSetToBeConverted.get(8,16);
byte[] temp = BitSetPart2.toByteArray();
int intPart2 = temp.length == 0 ? 0 : (int)(temp[0]); 

instead

Upvotes: 0

Related Questions