views:

359

answers:

5
+5  Q: 

huffman encoding

hiii... I am trying to implement the huffman algorithm for compression.. for that I have to write bits of variable length to a file.. is there any datatype in c++ to store bits in a file????

i tried using bitset<8> but its size is 4 bytes..so i cant use it since i am implementing compression..please help..

+7  A: 

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.

Bill the Lizard
+2  A: 

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
+2  A: 

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

Dan Hook
A: 

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.

Paul Nathan
+2  A: 

All the info you need on bit twiddling is here:
http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c

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).

Martin York