...
1 package utils
2
3 import (
4 "bytes"
5 "fmt"
6 "unicode"
7 )
8
9
10 func HexStr(buf []byte) string {
11 maxlen := 24
12 if len(buf) > maxlen {
13 buf = buf[:maxlen]
14 }
15 s := ""
16 deli := ""
17 for _, b := range buf {
18 s = s + deli + fmt.Sprintf("%02X", b)
19 deli = " "
20 }
21 s = s + " "
22 x := string(buf)
23 for _, r := range x {
24 if unicode.IsPrint(r) {
25 s = s + string(r)
26 } else {
27 s = s + "."
28 }
29 }
30 return s
31 }
32
33
34 func Hexdump(prefix string, buf []byte) string {
35 return HexdumpWithLen(60, prefix, buf)
36 }
37 func HexdumpWithLen(ln int, prefix string, buf []byte) string {
38 var res bytes.Buffer
39 linelen := 0
40 needprefix := true
41 ascii := ""
42 for _, b := range buf {
43 if needprefix {
44 res.WriteString(prefix)
45 }
46 needprefix = false
47 s := fmt.Sprintf("%02X ", b)
48 ascii = ascii + hextochar(b)
49 res.WriteString(s)
50 linelen = linelen + len(s)
51 if linelen >= ln {
52 linelen = 0
53 res.WriteString(ascii)
54 ascii = ""
55 res.WriteString("\n")
56 needprefix = true
57 }
58 }
59 if len(ascii) != 0 {
60 res.WriteString(ascii)
61 res.WriteString("\n")
62 }
63 return res.String()
64 }
65 func hextochar(b byte) string {
66 r := rune(b)
67 if !unicode.IsPrint(r) {
68 return "."
69 }
70 return string(r)
71
72 }
73
View as plain text