Reputation: 23
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:
Ideally, I'd rather use standard libraries. Thank you for any help in advance.
Upvotes: 1
Views: 166
Reputation: 25516
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), ...
Upvotes: 2