Huffman coding in Java

孤人 提交于 2019-12-11 06:15:36

问题


I want encode every file by Huffman code. I have found the length of bits per symbol (its Huffman code).

Is it possible to encode a character into a file in Java: are there any existing classes that read and write to a file bit by bit and not with minimum dimension of char?


回答1:


You could create a BitSet to store your encoding as you are creating it and simply write the String representation to a file when you are done.




回答2:


You really don't want to write single bits to a file, believe me. Usually we define a byte buffer, build the "file" in memory and, after all work is done, write the complete buffer. Otherwise it would take forever (nearly).

If you need a fast bit vector, then have a look at the colt library. That's pretty convenient if you want to write single bits and don't do all this bit shifting operations on your own.




回答3:


I'm sure there are Huffman classes out there, but I'm not immediately aware of where they are. If you want to roll your own, two ways to do this spring to mind immediately.

The first is to assemble the bit strings in memory my using mask and shift operators and accumulate the bits into larger data objects (i.e. ints or longs) and then write those out to file with standard streaming.

The second, more ambitious and self-contained idea would be to write an implementation of OutputStream that has a method for writing a single bit and then this OutputStream class would do the aforementioned buffering/shifting/accumulating itself and probably pass the results down to a second, wrapped OutputStream.




回答4:


Try writing a bit vector in java to do the bit representation: it should allow you to set/reset the individual bits in a bit stream.

The bit stream can thus hold your Huffman encoding. This is the best approach, and lightning fast too.

Huffmann sample analysis here




回答5:


You can find a working (and fast) implementation here: http://code.google.com/p/kanzi/source/browse/src/kanzi/entropy/HuffmanTree.java



来源:https://stackoverflow.com/questions/5790654/huffman-coding-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!