Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Storing bits in the most memory efficient manner

I have written an algorithm to implement Huffman Coding for compressing text files. It basically takes in a string as an input and generates a string of bits as output. However, I am having trouble storing this binary data as it is being stored as a string where each bit is a character and consumes 2 bytes of memory for storage. End result, output file is larger than the input, making the whole program worthless. How should I store this binary output such that each bit takes only one bit of memory for storage? ps. I have tried using a BitSet but that did not change the size of the output at all

like image 922
Prathamesh Avatar asked Nov 12 '22 20:11

Prathamesh


1 Answers

Once you have your result in the BitSet, you can call

BitSet.toByteArray() to save your data to a file, i.e.:

FileUtils.writeByteArrayToFile(new File(...), bitSet.toByteArray());

And BitSet.valueOf(byte[]) to read your data from file:

BitSet bitSet = new BitSet(FileUtils.readFileToByteArray(new File(...)));
like image 145
Andrey Chaschev Avatar answered Nov 15 '22 03:11

Andrey Chaschev