-1

fmt.Println(hex.Dump([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0}))

It shows:

00000000  01 02 03 04 05 06 07 08  09 00 01 02 03 04 05 06  |................|
00000010  07 08 09 00                                       |....|

How to add an indent before the hex addresses to all lines? like

    00000000  01 02 03 04 05 06 07 08  09 00 01 02 03 04 05 06  |................|
    00000010  07 08 09 00                                       |....|

Split the lines by \n then put an indent before each line will do, but is there any built-in tool does this? I tried hex.Dumper and tabwriter.NewWriter, but they just treat the indent as normal data and printed along with the hex dump.

2
  • 2
    You probably need to add a tab, or other indentation character(s) before each line. What have you tried? Feb 3, 2021 at 14:31
  • 1
    "but is there any built-in tool does this?" -- Not exactly this. But you can use a combination of bytes.Split and bytes.Join. Feb 3, 2021 at 14:54

1 Answer 1

2

hex.Dump() returns a formatted string. If you want it to be formatted like indenting every line, replace all newline characters with a newline + indentation (e.g. tab). Plus prepend the indentation to the start of it so the first line will also be indented (which is not preceeded by a newline char).

For replacing, use strings.ReplaceAll().

See this example:

s := hex.Dump([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0})
fmt.Println(s)

s = "\t" + strings.ReplaceAll(s, "\n", "\n\t")
fmt.Println(s)

Output (try it on the Go Playground):

00000000  01 02 03 04 05 06 07 08  09 00 01 02 03 04 05 06  |................|
00000010  07 08 09 00 01 02 03 04  05 06 07 08 09 00 01 02  |................|
00000020  03 04 05 06 07 08 09 00                           |........|

    00000000  01 02 03 04 05 06 07 08  09 00 01 02 03 04 05 06  |................|
    00000010  07 08 09 00 01 02 03 04  05 06 07 08 09 00 01 02  |................|
    00000020  03 04 05 06 07 08 09 00                           |........|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.