[英]Java: Storing bits in the most memory efficient manner
I have written an algorithm to implement Huffman Coding for compressing text files. 我编写了一个算法来实现Huffman Coding来压缩文本文件。 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.
但是,我在存储这个二进制数据时遇到了问题,因为它存储为一个字符串,其中每个位都是一个字符,并占用2个字节的内存用于存储。 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.
PS。 I have tried using a BitSet but that did not change the size of the output at all
我尝试过使用BitSet,但根本没有改变输出的大小
Once you have your result in the BitSet
, you can call 将结果
BitSet
,即可调用
BitSet.toByteArray()
to save your data to a file, ie: BitSet.toByteArray()
将数据保存到文件中,即:
FileUtils.writeByteArrayToFile(new File(...), bitSet.toByteArray());
And BitSet.valueOf(byte[])
to read your data from file: 和
BitSet.valueOf(byte[])
从文件中读取数据:
BitSet bitSet = new BitSet(FileUtils.readFileToByteArray(new File(...)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.