Binary BigEndian And Uvarint Wire Encoding

encoding/binary packs fixed-width integers in big-endian order for wire headers and shrinks small values into one-to-two-byte varints with AppendUvarint.

GoData Integrity

Code

gosnippet
28 lines
package main

import (
	"encoding/binary"
	"fmt"
)

func main() {
	// Fixed-width header: Magic(2 bytes) + Version(1 byte) + Length(4 bytes), all big-endian
	header := make([]byte, 7)
	binary.BigEndian.PutUint16(header[0:2], 0xD9F1)
	header[2] = 3
	binary.BigEndian.PutUint32(header[3:7], 1024)

	fmt.Printf("%x\n", header)

	// The peer reads it back with the same layout
	magic := binary.BigEndian.Uint16(header[0:2])
	version := header[2]
	length := binary.BigEndian.Uint32(header[3:7])
	fmt.Printf("magic=%x version=%d length=%d\n", magic, version, length)

	// Varint variable-length encoding: small numbers take 1-2 bytes, good for length prefixes
	varint := binary.AppendUvarint(nil, 300)
	fmt.Printf("uvarint(300) = %x (%d bytes)\n", varint, len(varint))
	value, n := binary.Uvarint(varint)
	fmt.Println("decoded:", value, "consumed:", n)
}

Under the hood

Binary BigEndian And Uvarint Wire Encoding reduces to the function main.

Caveats

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Using it

Running the file prints labeled results such as magic=, uvarint(300) =, decoded: — each operation’s effect is visible in the output.

Key statements

header := make([]byte, 7)

Interactive Tools for This Topic

FAQ

What does Binary BigEndian And Uvarint Wire Encoding print when run?
Run it as a complete program — the output lines carry labels such as `magic=`, `uvarint(300) =`, `decoded:`.