-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.

icza
  • 389,944
  • 63
  • 907
  • 827
aj3423
  • 2,003
  • 3
  • 32
  • 70

1 Answers1

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                           |........|
icza
  • 389,944
  • 63
  • 907
  • 827