Binary Serialization
Save games, cooked assets, network packets, replay files and the editor's undo buffer all need the same thing: turn in-memory objects into bytes, and bytes back into objects. Text formats (JSON, YAML, TOML) are great for source files that people edit and diff. At runtime, engines prefer binary: smaller, much faster to parse, and loadable with almost no allocation.
The save/load lesson covers what a save file should contain. This lesson covers how to write the bytes correctly.
The rules of a robust binary format
| Rule | Why |
|---|---|
| Start with a magic number | reject files that aren't yours ("is this even a save file?") |
| Store a format version | old saves must still load after you add fields |
| Fix the byte order (little-endian is the usual choice) | the same file must load on every platform |
Write fields one by one, never fwrite(&myStruct) |
struct padding, pointer members and layout differ between compilers |
| Prefix variable-length data with its length | strings and arrays can be read without scanning |
| Bounds-check every read | a truncated or corrupted file must fail cleanly, not crash |
Writer and reader
Here is a small pair of classes that follow those rules. Integers are written byte by byte, lowest byte first, so the result is little-endian on any machine; floats go through std::bit_cast to their 32-bit pattern.
#include <bit>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
class Writer {
public:
void u8(std::uint8_t v) { bytes.push_back(v); }
void u16(std::uint16_t v) { for (int i = 0; i < 2; i++) u8(std::uint8_t(v >> (8 * i))); }
void u32(std::uint32_t v) { for (int i = 0; i < 4; i++) u8(std::uint8_t(v >> (8 * i))); }
void i32(std::int32_t v) { u32(std::uint32_t(v)); }
void f32(float v) { u32(std::bit_cast<std::uint32_t>(v)); }
void str(const std::string& s) { u32(std::uint32_t(s.size())); bytes.insert(bytes.end(), s.begin(), s.end()); }
std::vector<std::uint8_t> bytes;
};
class Reader {
public:
explicit Reader(const std::vector<std::uint8_t>& b) : bytes_(b) {}
std::uint8_t u8() { need(1); return bytes_[pos_++]; }
std::uint16_t u16() { std::uint16_t v = 0; for (int i = 0; i < 2; i++) v |= std::uint16_t(u8()) << (8 * i); return v; }
std::uint32_t u32() { std::uint32_t v = 0; for (int i = 0; i < 4; i++) v |= std::uint32_t(u8()) << (8 * i); return v; }
std::int32_t i32() { return std::int32_t(u32()); }
float f32() { return std::bit_cast<float>(u32()); }
std::string str() { std::uint32_t n = u32(); need(n); std::string s(bytes_.begin() + pos_, bytes_.begin() + pos_ + n); pos_ += n; return s; }
private:
void need(std::size_t n) { if (pos_ + n > bytes_.size()) throw std::runtime_error("unexpected end of data at byte " + std::to_string(pos_)); }
const std::vector<std::uint8_t>& bytes_;
std::size_t pos_ = 0;
};
struct Entity { std::string name; float x, y; std::int32_t health; };
constexpr std::uint32_t kMagic = 0x53444154; // bytes 'T','A','D','S' when written little-endian
constexpr std::uint16_t kVersion = 2;
std::vector<std::uint8_t> save(const std::vector<Entity>& es) {
Writer w;
w.u32(kMagic); w.u16(kVersion); w.u32(std::uint32_t(es.size()));
for (const Entity& e : es) { w.str(e.name); w.f32(e.x); w.f32(e.y); w.i32(e.health); }
return w.bytes;
}
std::vector<Entity> load(const std::vector<std::uint8_t>& bytes) {
Reader r(bytes);
if (r.u32() != kMagic) throw std::runtime_error("not a TADS file");
std::uint16_t version = r.u16();
if (version > kVersion) throw std::runtime_error("file is from a newer version");
std::vector<Entity> es(r.u32());
for (Entity& e : es) { e.name = r.str(); e.x = r.f32(); e.y = r.f32(); e.health = r.i32(); }
return es;
}
int main() {
std::vector<Entity> world = {{"hero", 1.5f, -2.0f, 100}, {"slime", 8.25f, 0.0f, 12}};
auto blob = save(world);
std::cout << blob.size() << " bytes, first 32:\n";
for (std::size_t i = 0; i < 32; i++)
std::cout << std::hex << std::setw(2) << std::setfill('0') << int(blob[i]) << ((i % 16 == 15) ? "\n" : " ");
std::cout << std::dec << std::setfill(' ');
auto back = load(blob);
bool same = back.size() == world.size();
for (std::size_t i = 0; same && i < back.size(); i++)
same = back[i].name == world[i].name && back[i].x == world[i].x && back[i].y == world[i].y && back[i].health == world[i].health;
std::cout << "round trip identical: " << (same ? "yes" : "no") << "\n";
for (auto& e : back) std::cout << e.name << " (" << e.x << ", " << e.y << ") hp " << e.health << "\n";
blob.resize(blob.size() - 3); // simulate a truncated download
try { load(blob); } catch (const std::exception& ex) { std::cout << "truncated file: " << ex.what() << "\n"; }
}51 bytes, first 32:
54 41 44 53 02 00 02 00 00 00 04 00 00 00 68 65
72 6f 00 00 c0 3f 00 00 00 c0 64 00 00 00 05 00
round trip identical: yes
hero (1.5, -2) hp 100
slime (8.25, 0) hp 12
truncated file: unexpected end of data at byte 48
Read the hex dump left to right: 54 41 44 53 is the magic (TADS in ASCII), 02 00 the version, 02 00 00 00 the count, 04 00 00 00 the length of "hero", then its four letters, then 00 00 c0 3f, which is the float 1.5 in IEEE 754. Floats round-trip exactly because we copy their bits, not a printed decimal.
Note:
std::bit_cast(C++20,<bit>) is the legal way to reinterpret a float's bits. Areinterpret_cast<uint32_t*>(&f)or a union is undefined behaviour in C++, even though it usually works.
Versioning: loading old files
Version 1 of the format had no health field. When we added it, we bumped the version to 2. The loader reads the version first and fills in a default for fields an old file doesn't have:
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
// Compact writer/reader for this example (same byte layout as before).
struct W { std::vector<std::uint8_t> b; void u32(std::uint32_t v) { for (int i = 0; i < 4; i++) b.push_back(std::uint8_t(v >> (8 * i))); }
void str(const std::string& s) { u32(std::uint32_t(s.size())); b.insert(b.end(), s.begin(), s.end()); } };
struct R { const std::vector<std::uint8_t>& b; std::size_t p = 0;
std::uint32_t u32() { std::uint32_t v = 0; for (int i = 0; i < 4; i++) v |= std::uint32_t(b.at(p++)) << (8 * i); return v; }
std::string str() { std::uint32_t n = u32(); std::string s(b.begin() + p, b.begin() + p + n); p += n; return s; } };
struct Item { std::string id; std::uint32_t count; std::uint32_t durability; };
std::vector<Item> loadInventory(const std::vector<std::uint8_t>& bytes) {
R r{bytes};
std::uint32_t version = r.u32();
std::vector<Item> items(r.u32());
for (Item& it : items) {
it.id = r.str();
it.count = r.u32();
it.durability = version >= 2 ? r.u32() : 100; // field added in version 2
}
std::cout << "loaded version " << version << " file\n";
return items;
}
int main() {
W v1; v1.u32(1); v1.u32(2); // a save made before durability existed
v1.str("potion"); v1.u32(3);
v1.str("sword"); v1.u32(1);
W v2; v2.u32(2); v2.u32(1);
v2.str("sword"); v2.u32(1); v2.u32(37);
for (auto* file : {&v1.b, &v2.b})
for (const Item& it : loadInventory(*file))
std::cout << " " << it.id << " x" << it.count << ", durability " << it.durability << "\n";
}loaded version 1 file
potion x3, durability 100
sword x1, durability 100
loaded version 2 file
sword x1, durability 37
Keep every old branch for as long as old files exist in the wild. For saves, that is forever. Tests that load a stored v1, v2, v3… file on every build catch the day someone breaks an old path.
Beyond hand-written readers
- Reflection-driven serialization. Describe each component's fields once (a macro, a code generator, or a library such as EnTT's
meta, flecs' reflection, orrefl-cpp) and generate both the binary writer and the editor's property panel from it. - Schema-based formats. FlatBuffers and Cap'n Proto let you read fields straight from the buffer with no parsing step; Protocol Buffers is common for network messages. They handle versioning with field IDs.
- Memory-mapped cooked assets. Offline tools write data in the exact layout the runtime uses (offsets instead of pointers), so loading is one read and a pointer fix-up.
- Compression and checksums. Compress large blobs (LZ4 and Zstandard are popular) and store a checksum (CRC32, xxHash) to detect corruption before parsing.
Tip: Keep the text format around for development. Many engines store levels and prefabs as text in source control (readable diffs, mergeable) and "cook" them to binary in the build. See Scene Files and Prefabs.
Test yourself
Why shouldn't you fwrite a whole struct to a save file?
- fwrite is deprecated
- Padding, layout and pointer members vary between compilers and platforms, so the bytes aren't portable
- Structs can't be written to files
- It is slower than writing a field at a time
In the hex dump, what do the bytes 00 00 c0 3f represent?
- The integer 63
- The float 1.5 written little-endian
- The string length
- The format version
How does the inventory loader handle a version 1 file that lacks durability?
- It throws an error
- It reads garbage
- It checks the version and uses a default value of 100
- It rewrites the file