How to write a bit stream

I am thinking of writing some data to a bit stream using C. There are two options. One of them is to combine variable bit length characters into a continuous bit sequence, but so my decoder will probably find it difficult to separate these characters from this continuous bit stream. Another way is to distribute the same number of bits for which a character, and thus the decoder can easily restore the original data, but there may be a loss of bits, because the characters have different values, which, in turn, cause many bits in the bit stream, zero (these bits of waste, I think).

Any hint on what I should do?

I am new to programming. Any help would be appreciated.

+7
source share
1 answer

It looks like you're trying to do something similar to a Huffman compression scheme? I would just byte (char) and track the offset in the byte where I read the last character.

Assuming none of your characters are char anymore. It will look something like this:

struct bitstream { char *data; int data_size; // size of 'data' array int last_bit_offset; // last bit in the stream int current_data_offset; // position in 'data', ie data[current_data_offset] is current reading/writing byte int current_bit_offset; // which bit we are currently reading/writing } char decodeNextSymbol(bitstream *bs) { } int encodeNextSymbol(bitstream *bs, char symbol) { } 

The corresponding code for decodeNextSymbol and encodeNextSymbol will have to use the bitwise operations C ("&" (bitwise AND) and "|" (bitwise OR), for example. Then I would come up with a list of all of my characters starting with the shortest first and executing a while loop, which matches the shortest character. For example, if one of your characters is "101", then if the stream is "1011101", it will match the first "101" and will continue to match the rest of the stream '1101'. You will also have to handle the case when your values characters overflow from one th byte to another.

+2
source

All Articles