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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.