Ringo16
Ringo16

Reputation: 9

Can I input/output bits in C++

I am figuring out how to compress files and I was wondering if I could do bit manipulation with an output file.

Current I have a string of variable size n that contains only 0's and 1's. ex: 010111001010110

I want to output a file that contains only n bits instead of n characters.

Also, if that is possible, how can I read those bits back and convert it back into a string?

Thank you.

Update: If I cannot write out bits directly and have to pack it into bytes, does that mean I can convert the 8 bits into a char and just output a list of char? If so, what happens if I try to store "00000000", which means null?

Upvotes: 1

Views: 1392

Answers (2)

david scott
david scott

Reputation: 1

If you look the net for arb255.zip you will find my bijective arithmetic coder. The io used for program is BIT I/O of course the files are really in bytes. But the strings are bijective to the byte file. Its all handled in the includes but its true bijective bit IO as far as the main routines see.

Actually the old code for DJPP GNU C is at bijective.dogma.net some changes are needed to work in current C but the I/O should still work

Upvotes: 0

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

You can't write bits out directly, you have to pack them at least in eights. Yes, that means writing out bytes. Note that the output will be essentially padded to bytes and you have to do something about it.

To convert a string containing 0s and 1s to a raw data, the easiest way is to either use std::bitset, if you know the length, or write a loop that advances by eights, as in

for (auto i = 0; i < str.size(); i += 8)

Upvotes: 1

Related Questions