Hex Dump Rows With Offsets

Render arbitrary bytes as an offset-labeled hex dump with hex.EncodeToString and manual column math, the layout debuggers and protocol tools print.

GoCli Tooling

Code

gosnippet
40 lines
package main

import (
	"encoding/hex"
	"fmt"
	"strings"
)

func main() {
	data := []byte("devexamples hex dump\x00\x01\xff")

	// hex dump rows: 16 bytes per row, offset + hex + printable ascii columns
	const width = 16
	for offset := 0; offset < len(data); offset += width {
		end := offset + width
		if end > len(data) {
			end = len(data)
		}
		row := data[offset:end]

		fmt.Printf("%08x  %-*s |%s|\n",
			offset,
			width*3-1,
			hex.EncodeToString(row),
			asciiColumn(row))
	}
}

// asciiColumn:可打印字符原样输出,其余用点占位
func asciiColumn(row []byte) string {
	var b strings.Builder
	for _, c := range row {
		if c >= 0x20 && c < 0x7f {
			b.WriteByte(c)
		} else {
			b.WriteByte('.')
		}
	}
	return b.String()
}

How the snippet works

The snippet is organized around the functions main and asciiColumn.

The one repetition in this snippet is the loop for offset := 0; offset < len(data); offset += width.

Watch out for

  • Zero third-party dependencies — the runtime provides every API used here.

Putting it to use

Entry signature: func main()

Running the file executes main, which drives asciiColumn in order.

Core lines

for offset := 0; offset < len(data); offset += width {
end := offset + width
if end > len(data) {
end = len(data)
}
row := data[offset:end]
fmt.Printf("%08x  %-*s |%s|\n",
offset,
width*3-1,
hex.EncodeToString(row),
asciiColumn(row))
}
func asciiColumn(row []byte) string {
var b strings.Builder
for _, c := range row {
if c >= 0x20 && c < 0x7f {
b.WriteByte(c)
} else {
b.WriteByte('.')
}
}
return b.String()
}

Interactive Tools for This Topic

FAQ

How do you run Hex Dump Rows With Offsets?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.