How to write bit data to a file?

I have a std :: bitset that I would like to write to a file, bit for bit, but of course the fstream write function does not support this. I can't think of any other way than converting each 8-bit group to char using a string and a record that ...

Does anyone know a good way?

+2
source share
2 answers

Try:

#include <bitset>
#include <fstream>

int main() {
    using namespace std;
    const bitset<12> x(2730ul); 
    cout << "x =      " << x << endl;

    ofstream ofs("C:\\test.txt"); // write as txt
    if (ofs) {
        // easy way, use the stream insertion operator
        ofs << x << endl;

        // using fstream::write()
        string s = x.to_string();
        ofs.write(s.c_str(), s.length()); 
    }
    return 0;
}
+2
source

, "" - . , , - to_string(), . < → , utlize constructor to_string() . .

, , ( ), , , , . , , .

0

All Articles