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.
Code
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
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 Varint Packs Signed Integers print when run?
- The script runs standalone; its 3 labeled outputs include `mismatch:`, `read:`, `total bytes:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.