Golang:如何打印结构中的字节的 % x ?

sam*_*mol 6 printf byte go

var b [88]byte
n, err := file.Read(b[:])
fmt.Printf("bytes read: %d Bytes: [% x]\n", n, b)
Run Code Online (Sandbox Code Playgroud)

上面以十六进制打印字节

我有一个这样的结构

type SomeStruct struct {
   field1 []byte
   field2 []byte
}
someStructInstance := SomeStruct{[249 190 180 217], [29 1 0 0]}
fmt.Println(someStructInstance)
=> {[249 190 180 217] [29 1 0 0]}
Run Code Online (Sandbox Code Playgroud)

但理想情况下我希望它打印十六进制

=> {[f9 be b4 d9] [1d 01 00 00]}
Run Code Online (Sandbox Code Playgroud)

我该怎么办呢?

Dav*_*son 5

我认为你只需要String在 上定义你自己的函数SomeStruct。这是一个例子:

package main

import "fmt"

type SomeStruct struct {
   field1 []byte
   field2 []byte
}

func (s SomeStruct) String() string {
  return fmt.Sprintf("{[% x] [% x]}", s.field1, s.field2)
}

func main() {
  someStructInstance := SomeStruct{[]byte{249, 190, 180, 217}, []byte{29, 1, 0, 0}}
  fmt.Println(someStructInstance)
}
Run Code Online (Sandbox Code Playgroud)

在 Go Playground 上运行时查看: http://play.golang.org/p/eYBa1n33a2


zmb*_*zmb 3

您可以使用反射来检查结构并打印[]byte它所具有的任何内容。

package main

import (
    "fmt"
    "reflect"
)

type SomeStruct struct {
    field1 []byte
    field2 []byte
}

type OtherStruct struct {
    intValue  int
    intSlice  []int
    byteSlice []byte
}

var typeOfBytes = reflect.TypeOf([]byte(nil))

func printSlicesHex(obj interface{}) {
    value := reflect.ValueOf(obj)
    typeOfObj := value.Type()
    for i := 0; i < value.NumField(); i++ {
        field := value.Field(i)
        if field.Type() == typeOfBytes {
            bytes := field.Bytes()
            printBytes(typeOfObj.Field(i).Name, bytes)
        }
    }
}

func printBytes(name string, bytes []byte) {
    fmt.Printf("%s: [% x]\n", name, bytes)
}

func main() {
    someStructInstance := SomeStruct{[]byte{249, 190, 180, 217}, []byte{29, 1, 0, 0}}
    fmt.Println("Printing []bytes in SomeStruct")
    printSlicesHex(someStructInstance)
    fmt.Println()

    otherStruct := OtherStruct{0, []int{0, 1, 2}, []byte{0, 1, 2, 3}}
    fmt.Println("Printing []bytes in OtherStruct")
    printSlicesHex(otherStruct)
}
Run Code Online (Sandbox Code Playgroud)

对于每个[]byte,此示例打印字段的名称及其数据(以十六进制表示)。您可以通过使用自定义函数来进行打印来改进这一点,这样您就不必总是以十六进制打印。

游乐场链接