Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BitSet and byte[] usage

I have this application where I should use BitSet class heavily and write to a file bit by bit. I know I can't write bits to a file, so first I convert the BitSet object to byte array and write as byte array. But the problem is since BitSet class indexed from right to left, when I convert the BitSet object to byte array and write to a file, it writes backwards.

For example this is my BitSet object:

10100100

and BitSet.get(0) gives false, and BitSet.get(7) gives true. I want to write this to file like:

00100101

so first bit will be 0 and last bit will be 1.

My convert method:

public static byte[] toByteArray(BitSet bits) 
{
    byte[] bytes = new byte[(bits.length() + 7) / 8];       
    for (int i = 0; i < bits.length(); i++) {
        if (bits.get(i)) {
            bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
        }
    }
    return bytes;
}

My write method:

    FileOutputStream fos = new FileOutputStream(filePath);
    fos.write(BitOperations.toByteArray(cBitSet));
    fos.close();

Is this intended to be like this or am I doing something wrong? Thank you.

like image 684
gmnnn Avatar asked Dec 25 '12 16:12

gmnnn


1 Answers

BitSet implements Serializable. If you only need to be able to restore the BitSet in Java, and don't need to otherwise examine its state in the file, you should just tell it to save itself to the file.

If you wish to write it to a file that contains other, non-serialized data, you can write it to a ByteArrayOutputStream and retrieve the byte[] from that. However, you will probably get better performance writing directly to the file.

like image 78
Patricia Shanahan Avatar answered Sep 22 '22 11:09

Patricia Shanahan