Skip to content

Instantly share code, notes, and snippets.

@chmike
Last active June 3, 2024 21:58
Show Gist options
  • Save chmike/05da938833328a9a94e02506922f2e7b to your computer and use it in GitHub Desktop.
Save chmike/05da938833328a9a94e02506922f2e7b to your computer and use it in GitHub Desktop.
Go language function to dump a byte slice in hexadecimal and ASCII
func dumpByteSlice(b []byte) {
var a [16]byte
n := (len(b) + 15) &^ 15
for i := 0; i < n; i++ {
if i%16 == 0 {
fmt.Printf("%4d", i)
}
if i%8 == 0 {
fmt.Print(" ")
}
if i < len(b) {
fmt.Printf(" %02X", b[i])
} else {
fmt.Print(" ")
}
if i >= len(b) {
a[i%16] = ' '
} else if b[i] < 32 || b[i] > 126 {
a[i%16] = '.'
} else {
a[i%16] = b[i]
}
if i%16 == 15 {
fmt.Printf(" %s\n", string(a[:]))
}
}
}
@chmike
Copy link
Author

chmike commented Mar 13, 2019

The instruction

dumpByteSlice([]byte{10, 2, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80})

will print the following to stdOut

   0  0A 02 40 41 42 43 44 45  46 47 48 49 4A 4B 4C 4D  ..@ABCDEFGHIJKLM
  16  4E 4F 50                                          NOP             

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment