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.