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
  • 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 Commented Nov 1, 2015 at 0:21

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

Comments

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();

}

4 Comments

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.
if you run the above code the file file.txt will contain 0110110101011110110010010000010. what do you mean ?
@waterisawesome: you can check my approach
He wants the binary data in the file to be that, not a sequence of characters that happens to be '0' and '1'
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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.