How to write bitset data to a file? [duplicate]

2019-01-25 21:50发布

问题:

This question already has an answer here:

  • How does one store a vector<bool> or a bitset into a file, but bit-wise? 6 answers

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?

回答1:

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:

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.