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.
Code
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
Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.CSS Color ConverterConvert colors between HEX, rgb(), and hsl() instantly, with support for shorthand hex and rgb or hsl inputs. Fully offline and dependency free.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.