Varint Packs Signed Integers

Store signed integers in one to ten bytes with binary.PutVarint, and walk the buffer back with binary.Varint to recover each value and its width.

GoCli Tooling

Code

gosnippet
30 lines
package main

import (
	"encoding/binary"
	"fmt"
)

func main() {
	// PutVarint 把有符号整数编码成 1-10 字节的紧凑序列:
	// 符号信息挪进最低有效位,绝对值小的负数同样省字节
	buf := make([]byte, binary.MaxVarintLen64)
	for _, n := range []int64{0, 1, -1, 64, -64, 300, 1 << 20} {
		written := binary.PutVarint(buf, n)
		fmt.Printf("%d -> %d bytes %x
", n, written, buf[:written])
	}

	// 解码端逐条读回:Varint 返回值与消耗的字节数
	offset := 0
	for _, want := range []int64{0, 1, -1, 64, -64, 300, 1 << 20} {
		value, read := binary.Varint(buf[offset:])
		if value != want {
			fmt.Println("mismatch:", value, "want", want)
			return
		}
		fmt.Println("read:", value, "consumed", read)
		offset += read
	}
	fmt.Println("total bytes:", offset)
}

Where the workload sits

Read the whole thing as the function main, doing all the work.

One loop does the cycling here: for _, n := range []int64{0, 1, -1, 64, -64, 300, 1 << 20}.

What to watch for

  • The runtime alone is required; there are no packages and no install.

Applying it

The entry-point signature is func main()

The file’s steps show up in the output as mismatch:, read:, total bytes:.

Statements that matter

for _, want := range []int64{0, 1, -1, 64, -64, 300, 1 << 20} {
	value, read := binary.Varint(buf[offset:])
	if value != want {
		fmt.Println("mismatch:", value, "want", want)
		return
	}
	fmt.Println("read:", value, "consumed", read)
	offset += read
}
for _, n := range []int64{0, 1, -1, 64, -64, 300, 1 << 20} {
	written := binary.PutVarint(buf, n)
	fmt.Printf("%d -> %d bytes %x
", n, written, buf[:written])
}
buf := make([]byte, binary.MaxVarintLen64)

Interactive Tools for This Topic

FAQ

What does Varint Packs Signed Integers print when run?
The script runs standalone; its 3 labeled outputs include `mismatch:`, `read:`, `total bytes:`.