Question

This question already has an answer here:

I have a std::bitset that I'd like to write to a file, bit for bit, but of course fstream's write function doesn't support this. I can't think of another way besides converting each 8-bit group to a char using string and writing that...

Anyone know of a good way?

Was it helpful?

Solution

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

OTHER TIPS

Well, "a" way of doing it is to use string as your serialization method. There is a bitset constructor that takes a string argument, and there is a to_string() member function that returns one. There are also << and >> helper operators that use that utlize the constructor and to_string() function for stream insertion and extraction. That may work for you depending on your requirements.

That wasn't compact enough for us in one application, so we ended up writing a class that looks like bitset (has the same interface) but it is also serializable as a stream of bytes, meaning it has functions that return pointers to the underlying byte array that makes it up. It wasn't too terribly hard to write if you have the source to several implementations to look at.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top