binary text to real binary

Can't figure this out. Help would be appreciated.

At a certain point i and up with a 'string' of characters having only binaries (0 and 1 are '0' and '1'). Saving as 'text' wouldn't be very efficient. How can i output the data as pure binary code?

Construct bitset out of it and then save bitset as a number. std::bitset has a constructor taking string.

Edit: example code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <bitset>
#include <iostream>
#include <sstream>
#include <string>

size_t save_as_binary(std::ostream& out, std::string binary)
{
    size_t padding = 8 - binary.size() % 8;
    if(padding == 8) padding = 0;
    binary.insert(0, padding, '0');

    for(size_t pos = 0; pos < binary.size(); pos += 8) {
        std::bitset<8> bits(binary, pos, 8);
        unsigned char data = bits.to_ulong();
        out.write((char*)&data, 1);
    }
    return binary.size() / 8;
}

std::string read_as_binary(std::istream& in, size_t bytes)
{
    std::string result;
    for(size_t i = 0; i < bytes; ++i) {
        unsigned char data;
        in.read((char*)&data, 1);
        std::bitset<8> bits(data);
        result += bits.to_string();
    }
    return result;
}

int main()
{
    std::string binary = "110010100111101101000101101";
    std::stringstream ss(std::ios::binary | std::ios::in | std::ios::out);
    size_t bytes = save_as_binary(ss, std::move(binary));
    binary = read_as_binary(ss, bytes);
    std::cout << binary;
}

Last edited on
Thnx MiiNiPaa

Isn't there an easier way. Somewhat like streaming the data to file (which is binary anyway)?
Isn't there an easier way. Somewhat like streaming the data to file
Yes.
file << "1101010111". But this will waste one byte per character. If you want 1 byte per 8 character, you need to manually pack it first, then stream data into file.
Last edited on
Topic archived. No new replies allowed.