Huffman encoding

I am trying to implement a huffman compression algorithm that requires writing bits of variable length to a file. Is there a way in C ++ to write variable-length data with 1-bit granularity to a file?

+7
c ++ compression huffman-code
source share
5 answers

No, the smallest amount of data that you can write to a file is one byte.

You can use bitset to make it easier to manipulate bits, then use ofstream to write to the file. If you do not want to use bit set, you can use bitwise operators to manage your data before saving.

+9
source share

The smallest number of bits you can get and save is 8 = 1 byte. You can access bits in bytes using the ^ and | bitwise operators.

You can set the nth bit to 1 using:

my_byte = my_byte | (1 << n); 

where n is 0-7.

You can set the nth bit to 0 using:

 my_byte = my_byte & ((~1) << n); 

You can switch the nth bit using:

 my_byte = my_byte ^ (1 << n); 

More details here .

+3
source share

The answer to klew is probably the one you want, but just to add something to what Bill said, the Boost libraries have dynamic_bitset , which I found useful in a similar situation.

+2
source share

All the information needed for bit-scripting is here:
How do you set, clear and switch one bit?

But the smallest object you can put in a file is a byte.
I would use dynamic_bitset, and every time the size becomes more than 8, extract the bottom 8 bits in char and write this to a file, then move the remaining bits to 8 places (repeat).

+2
source share

Not. You will have to pack the bytes. Accordingly, you will need a heading in your file that indicates how many elements are in your file, because you will most likely have no unused bits.

+1
source share

All Articles