简体   繁体   中英

huffman encoding

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

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

You can use a bitset to make manipulating bits easier, then use an ofstream to write to file. If you don't want to use bitset, you can use the bitwise operators to manipulate your data before saving it.

The smallest amount of bits you can access and save is 8 = 1 byte. You can access bits in byte using bit operators ^ & |.

You can set n'th bit to 1 using:

my_byte = my_byte | (1 << n);

where n is 0 to 7.

You can set n'th bit to 0 using:

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

You can toggle n'th bit using:

my_byte = my_byte ^ (1 << n);

More details here .

klew的答案可能就是你想要的答案,但只是为了添加Bill所说的内容,Boost库有一个dynamic_bitset ,我发现它在类似的情况下很有帮助。

All the info you need on bit twiddling is here:
How do you set, clear, and toggle a single bit?

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

No. You will have to pack bytes. Accordingly, you will need a header in your file that specifies how many elements are in your file, because you are likely to have trailing bits that are unused.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM