Serializing binary data in C++

The following is a simple program to serialize data:

#include <fstream>

int main()
{
        int c = 3;
        std::ofstream f("a.txt");
        f << c;

        return 0;
}

Build and run it on Unix OSs (I test on both OpenBSD and Linux):

# c++ test.cc -o test
# ./test
# hexdump -C a.txt
00000000  33                                                |3|
00000001

We can see the integer 3 is saved in text mode, 0x33, which notates ‘3‘ in ASCII. Change the opening file mode to binary:

std::ofstream f("a.txt", std::ios_base::binary);

You will get the same result. So if you want to dump binary data, you may use write function provided by ostream in C++:

# cat test.cc
#include <fstream>

int main()
{
        int c = 3;
        std::ofstream f("a.txt");
        f.write(reinterpret_cast<char*>(&c), sizeof(c));

        return 0;
}
# c++ test.cc -o test
# ./test
# hexdump -C a.txt
00000000  03 00 00 00                                       |....|
00000004

Similarly, istream‘s read can be used to fetch binary data in serialization.

P.S., the full code is here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.