TExcelTAD
Home › Multiplayer Game Networking › Serialization & Bit-Packing

Serialization & Bit-Packing

Serialization turns game state into bytes and back. For a web API, JSON is fine. For a game server sending 30 snapshots per second to 64 players, the format decides whether the game fits in a player's upload bandwidth, so games use compact binary formats and often pack values into bits rather than whole bytes.

JSON vs binary

The same player update, written three ways:

ts · try it yourself
const player = { id: 7, x: 312.5, y: 88.25, angle: 1.5708, health: 87, flags: { crouch: true, firing: false, reloading: true } };

// 1. JSON text
const json = JSON.stringify(player);

// 2. Plain binary with DataView: fixed-size fields, little-endian
const buf = new ArrayBuffer(1 + 4 + 4 + 4 + 1 + 1);
const dv = new DataView(buf);
let o = 0;
dv.setUint8(o, player.id); o += 1;
dv.setFloat32(o, player.x, true); o += 4;
dv.setFloat32(o, player.y, true); o += 4;
dv.setFloat32(o, player.angle, true); o += 4;
dv.setUint8(o, player.health); o += 1;
dv.setUint8(o, (+player.flags.crouch) | (+player.flags.firing << 1) | (+player.flags.reloading << 2)); o += 1;

console.log(`JSON:   ${new TextEncoder().encode(json).length} bytes  ${json}`);
console.log(`binary: ${o} bytes   ${[...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join(' ')}`);

// Reading it back must use exactly the same order, sizes and endianness.
const r = new DataView(buf);
console.log('decoded:', r.getUint8(0), r.getFloat32(1, true), r.getFloat32(5, true), r.getFloat32(9, true).toFixed(4), r.getUint8(13), (r.getUint8(14) & 0b100) !== 0);
JSON:   111 bytes  {"id":7,"x":312.5,"y":88.25,"angle":1.5708,"health":87,"flags":{"crouch":true,"firing":false,"reloading":true}}
binary: 15 bytes   07 00 40 9c 43 00 80 b0 42 f9 0f c9 3f 57 05
decoded: 7 312.5 88.25 1.5708 87 true

The binary version is more than seven times smaller (15 bytes instead of 111), and it has no field names: both sides must agree on the layout. That agreement is the protocol, and changing it means both sides must change together (which is why games check a protocol version on connect).

Packing bits

Most game values don't need 8, 16 or 32 bits. A player id in a 16-player match needs 4 bits; health from 0 to 100 needs 7; a "crouching" flag needs 1. A bit writer appends values of any width to a buffer:

ts · try it yourself
class BitWriter {
  private bytes: number[] = [];
  private bit = 0;                       // total bits written
  write(value: number, bits: number) {
    for (let i = 0; i < bits; i++) {     // least significant bit first
      const byte = this.bit >> 3;
      if (byte === this.bytes.length) this.bytes.push(0);
      if ((value >> i) & 1) this.bytes[byte] |= 1 << (this.bit & 7);
      this.bit++;
    }
  }
  get bitLength() { return this.bit; }
  toBytes() { return Uint8Array.from(this.bytes); }
}

class BitReader {
  private bit = 0;
  constructor(private bytes: Uint8Array) {}
  read(bits: number): number {
    let v = 0;
    for (let i = 0; i < bits; i++) {
      if (this.bit >> 3 >= this.bytes.length) throw new Error('read past end of packet');
      if ((this.bytes[this.bit >> 3] >> (this.bit & 7)) & 1) v |= 1 << i;
      this.bit++;
    }
    return v;
  }
}

const w = new BitWriter();
w.write(7, 4);        // player id 0..15
w.write(87, 7);       // health 0..100
w.write(1, 1);        // crouching
w.write(0, 1);        // firing
w.write(1, 1);        // reloading
w.write(3, 2);        // weapon slot 0..3
console.log(`${w.bitLength} bits -> ${w.toBytes().length} bytes:`, [...w.toBytes()].map((b) => b.toString(2).padStart(8, '0')).join(' '));

const rd = new BitReader(w.toBytes());
console.log({ id: rd.read(4), health: rd.read(7), crouch: rd.read(1), firing: rd.read(1), reloading: rd.read(1), slot: rd.read(2) });
try { rd.read(8); } catch (e) { console.log('error:', (e as Error).message); }
16 bits -> 2 bytes: 01110111 11101101
{ id: 7, health: 87, crouch: 1, firing: 0, reloading: 1, slot: 3 }
error: read past end of packet

Sixteen bits, 2 bytes, for six fields that take 6 bytes with one byte each, or 24 bytes as 32-bit ints. Positions and angles get the same treatment through quantization in the next lesson.

Rules for a packet format

  1. One writer and one reader per message, kept side by side. The classic bug is changing one and not the other. Many libraries use a single Serialize(stream) function that both reads and writes depending on the stream's mode, so they can't drift apart (Unity NGO's INetworkSerializable.NetworkSerialize<T>(BufferSerializer<T>) works this way).
  2. Validate while reading. A packet is untrusted input from the internet. Check lengths before reading, reject values out of range (a player id of 15 in a 4-player game), and never allocate based on a length field without a cap. A malicious "array of 2 billion items" must not crash the server.
  3. Fix the endianness. Pick little-endian (what x86 and ARM use) and write it explicitly, as DataView and BinaryPrimitives let you.
  4. Version the protocol. Send a protocol version (or a hash of the message schema) in the connect request and refuse mismatches with a clear "please update" message.
  5. Don't serialize floats you can't reproduce. For lockstep and rollback (Deterministic Lockstep) the simulation itself must be bit-exact; serialization is the easy part.

The same thing in C#

C# servers and Unity/Godot .NET clients use Span<byte> and System.Buffers.Binary.BinaryPrimitives, which write without allocating:

csharp · try it yourself
using System;
using System.Buffers.Binary;

Span<byte> packet = stackalloc byte[12];
BinaryPrimitives.WriteUInt16LittleEndian(packet.Slice(0, 2), 4211);      // sequence number
BinaryPrimitives.WriteUInt32LittleEndian(packet.Slice(2, 4), 987654);    // server tick
BinaryPrimitives.WriteSingleLittleEndian(packet.Slice(6, 4), 312.5f);    // x
BinaryPrimitives.WriteInt16LittleEndian(packet.Slice(10, 2), -42);       // vertical velocity * 10

Console.WriteLine(Convert.ToHexString(packet));
Console.WriteLine(
quot;seq {BinaryPrimitives.ReadUInt16LittleEndian(packet)}, " +
quot;tick {BinaryPrimitives.ReadUInt32LittleEndian(packet.Slice(2))}, " +
quot;x {BinaryPrimitives.ReadSingleLittleEndian(packet.Slice(6))}, " +
quot;vy {BinaryPrimitives.ReadInt16LittleEndian(packet.Slice(10)) / 10.0}");
731006120F0000409C43D6FF
seq 4211, tick 987654, x 312.5, vy -4.2

Schema tools

Writing serializers by hand is fine for a small game and teaches you what is going on. Larger projects generate them from a schema or let the engine do it: engines serialize replicated variables for you (Unity Netcode, Unreal Replication), Colyseus uses its own schema encoder, and general-purpose formats such as Protocol Buffers, FlatBuffers and MessagePack are common for backend messages (matchmaking, inventories) where a few extra bytes don't matter.

Test yourself

How many bits does a value from 0 to 100 need?

  1. 6
  2. 7
  3. 8
  4. 100

A packet says it contains 3,000,000,000 items. What should the server do?

  1. Allocate the array and read them
  2. Reject the packet: lengths from the network must be checked against a sane maximum
  3. Read 3 billion bits
  4. Ask the client to resend

Why do some libraries use one Serialize function for both reading and writing?

  1. It is faster at runtime
  2. The read and write code can't drift apart, because they are the same code
  3. It compresses better
  4. It is required by UDP