1

Let's say I have a string that contains a binary like this one "0110110101011110110010010000010". Is there a easy way to output that string into a binary file so that the file contains 0110110101011110110010010000010? I understand that the computer writes one byte at a time but I am having trouble coming up with a way to write the contents of the string as a binary to a binary file.

  • 1
    First you have to convert the string into binary data. Then, write that data to a file. BTW, your string won't perfectly map to a file, because it doesn't have the right number of bits – Daniel Nov 01 '15 at 00:21

3 Answers3

4

Use a bitset:

//Added extra leading zero to make 32-bit.
std::bitset<32> b("00110110101011110110010010000010");

auto ull = b.to_ullong();

std::ofstream f;
f.open("test_file.dat", std::ios_base::out | std::ios_base::binary);
f.write(reinterpret_cast<char*>(&ull), sizeof(ull));
f.close();
Casey
  • 10,297
  • 11
  • 59
  • 88
0

I am not sure if that's what you need but here you go:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
    string tmp = "0110110101011110110010010000010";
    ofstream out;
    out.open("file.txt");
    out << tmp;
    out.close();

}
KostasRim
  • 2,053
  • 1
  • 16
  • 32
  • Unfortunately, this is not what I am looking for. Your output will be in text format and the equivalent of that in binary will be 0x30313130..... What I am looking for is the file containing the binary 0110110101011110110010010000010. Hopefully, I made sense there. – waterisawesome Nov 01 '15 at 00:38
  • if you run the above code the file file.txt will contain 0110110101011110110010010000010. what do you mean ? – KostasRim Nov 01 '15 at 00:43
  • @waterisawesome: you can check my approach – Giorgi Moniava Nov 01 '15 at 00:44
  • He wants the binary data in the file to be that, not a sequence of characters that happens to be '0' and '1' – Neil Kirk Nov 01 '15 at 00:49
0

Make sure your output stream is in binary mode. This handles the case where the string size is not a multiple of the number of bits in a byte. Extra bits are set to 0.

const unsigned int BitsPerByte = CHAR_BIT;
unsigned char byte;
for (size_t i = 0; i < data.size(); ++i)
{
    if ((i % BitsPerByte) == 0)
    {
        // first bit of a byte
        byte = 0;
    }
    if (data[i] == '1')
    {
        // set a bit to 1
        byte |= (1 << (i % BitsPerByte));
    }
    if (((i % BitsPerByte) == BitsPerByte - 1) || i + 1 == data.size())
    {
        // last bit of the byte
        file << byte;
    }
}
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91