My program stores Huffman code in a char[8]
variable. I want to store it in an unsigned char
variable. I do it, but don't think it works correctly because when I used the following code to extract my file it didn't work:
unsigned char bit2byte (开发者_C百科 unsigned char bits[8] ) {
unsigned char x = 0;
for ( int k = 0; k < 8; k++ ) {
if ( bits[k] == '1' )
x = x | 1;
x <<= 1;
}
return x;
}
What about this line:
if ( bits[k] == '1' )
does the bits
array store your bits as ASCII characters or as digital values, i.e. what happens if you try
if ( bits[k] == 0x01 )
You'll probably downvote me for not being able to read your mind...
Huffman is an compression scheme, and if you want to read a Huffman encoded file you most likly want to decode it (i.e. uncompress it)
http://en.wikipedia.org/wiki/Huffman_coding
In Huffman encoded data, each character is represented as a variable number of bits, and hence you cannot process a file by simply passing in a fixed portion of a file expecting to return a single byte in each call -- you have to keep state of how many bits are consumed in each call, and where to start processing in the bit stream for the extracting the next byte.
To correctly decode Huffman data, you will need the encoding tree (see the wikipedia link) -- this tree is most likely stored within the files as well -- so really your file will most likely have two parts: (1) The encoding/decoding tree, and (2) the data -- how that is stored in the file is implementation specific, so you will need the specification for that first before you attempt to decode anything.
Hope this helps.
I'm not clear on what you mean by "doesn't work" but it could be you need to go the other way.
for (int k = 7; k >= 0; k--) {
and everything else as before.
Of course, I also don't know why you ever use 8 bytes to store only 8 bits of information.
精彩评论