{
  "slug": "zigzag-encoding",
  "term": "ZigZag encoding",
  "aliases": [
    "Zig-zag encoding"
  ],
  "definition": "ZigZag encoding maps signed integers to unsigned integers so that values near zero remain small before variable-length encoding.",
  "note": "Mapping: Use 2n for nonnegative n and -2n-1 for negative n. This maps 0, -1, 1, -2, 2 to 0, 1, 2, 3, 4. The mapping precedes byte encoding; it is not byte order or encryption. [varint-protobuf]\n\nDeclared types: Protobuf sint32 and sint64 use ZigZag; int32 and int64 do not, and their negative values require ten varint bytes. The schema changes the interpretation. [varint-protobuf]\n\nAvro: Binary int and long use variable-length ZigZag coding: -64 becomes hexadecimal 7f, while 64 becomes 80 01. Readers also need the writer schema. [varint-avro]\n\nArithmetic: A signed 64-bit minimum maps to the unsigned 64-bit maximum. Implement the formula within the intended width; language-specific shifts and overflow need explicit handling. [varint-protobuf]",
  "related": [
    "variable-length-integer",
    "data-serialization",
    "stream-vbyte",
    "rice-coding",
    "protocol-buffers"
  ],
  "citations": [
    {
      "id": "varint-protobuf",
      "title": "Protocol Buffers encoding: Base 128 Varints and Signed Integers",
      "url": "https://protobuf.dev/programming-guides/encoding/",
      "accessed": "2026-11-17"
    },
    {
      "id": "varint-avro",
      "title": "Apache Avro 1.12.0: Binary Encoding and writer schemas",
      "url": "https://avro.apache.org/docs/1.12.0/specification/#binary-encoding",
      "accessed": "2026-11-17"
    }
  ],
  "status": "unknown",
  "advantages": [],
  "limitations": [],
  "supersedes": [],
  "supersededBy": [],
  "firstSeen": null,
  "lastSeen": null,
  "updated": "2026-11-21",
  "provenance": [
    "Source synthesis and exact integer examples, not a full serializer or a native decoder conformance test.",
    "Executable examples and controls: https://hesela.dev/research/varint-contracts.mjs and https://hesela.dev/research/varint-contracts.test.mjs."
  ]
}
