简体   繁体   中英

Writing a large binary string to a binary file

I have a large (122k length) string of 0s and 1s (010011101...) that needs to be written to a binary file as 0s and 1s and not their character representations.

What I've tried:

  • Outputting a Binary String to a Binary File in C++ - This is a good solution, however, I will have multiple strings of varying sizes and bitset needs a size at runtime as far as I know.
  • Stanford C++ library has a writebit function which works, but this takes way, way too long since each bit opens a write function.
  • different ways of implementing outputfile.write(), but they all write the character representations of the 0s and 1s.

Ideally, I'd rather use standard libraries. Thank you for any help in advance.

You can combine eight bits each into one character:

int n = 0;
uint8_t value = 0;
for(auto c : str)
{
    value |= static_cast<unint8_t>(c == '1') << n;
    if(++n == 8)
    {
        // print value or buffer it elsewhere, if you want
        // to print greater chunks at once
        n = 0;
        value = 0;
    }
}
if(n != 0)
{
    // one partial byte left
}

Bytes have a fixed number of bits (eight usually), and you cannot just discard them, they will go into your file. So you need some way to specify, when decoding again, how many bits to discard. You might append an additional byte how many bits are valid in very last byte, you might encode total number of bits by some means (and could check if sufficent bytes have been read), ...

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