问题
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:
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();
回答2:
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();
}
回答3:
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;
}
}
来源:https://stackoverflow.com/questions/33457974/outputting-a-binary-string-to-a-binary-file-in-c