waterisawesome
waterisawesome

Reputation: 13

Outputting a Binary String to a Binary File in C++

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.

Upvotes: 1

Views: 737

Answers (3)

Casey
Casey

Reputation: 10976

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

Upvotes: 4

Neil Kirk
Neil Kirk

Reputation: 21813

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;
    }
}

Upvotes: 0

KostasRim
KostasRim

Reputation: 2053

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

}

Upvotes: 0

Related Questions