binary text to real binary

Oct 12, 2015 at 9:46pm
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?

Oct 12, 2015 at 10:14pm
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 Oct 12, 2015 at 10:34pm
Oct 12, 2015 at 11:59pm
Thnx MiiNiPaa

Isn't there an easier way. Somewhat like streaming the data to file (which is binary anyway)?
Oct 13, 2015 at 7:20am
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 Oct 13, 2015 at 7:20am
Topic archived. No new replies allowed.