views:

504

answers:

2

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?

+2  A: 

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;
}
dirkgently
not sure I understand... what is 'mask'? Why do you create a const bitset and then another with the same name?
Tony R
Updated my answer, take a look! Those were artifacts from quick edits of SGI's bitset example.
dirkgently
Okay great. Works with ofstream operator<< but not fstream.write()... check.
Tony R
Added fstream::write() example as well.
dirkgently
You can save 87.5% space by packing groups of 8 bits into a byte and writing the output as binary.
marcog
A: 

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.

Brian Neal