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