设置 %s 从字节编码的十六进制到变量 golang

请原谅我对这门语言的陌生。我找到了这个编码为字节的示例,然后它使用 输出fmt.Printf,但是我如何将这个示例的字符串表示形式存储在变量中呢?


src := []byte("Hello Gopher!")


dst := make([]byte, hex.EncodedLen(len(src)))

hex.Encode(dst, src)


fmt.Printf("%s\n", dst) // output: 48656c6c6f20476f7068657221 (how do I get this output rather in a variable?

我想设置dst一个变量,以便稍后在代码中使用,而不是将其打印出来。

我试图弄清楚如何格式化 a hexwhich which was encoded from bytebut the example is printed out in fmt.Printfusing %s. 但我想格式化以在一个变量中使用,该变量可以在后面部分的代码中重用。所以我不认为这是标记原因的重复,因为它涉及格式化字符串,而不是字节的十六进制


ibeautiful
浏览 113回答 1
1回答

慕码人8056858

例如,package mainimport (    "encoding/hex"    "fmt")func main() {    str := "Hello Gopher!"    fmt.Println(str)    src := []byte(str)    fmt.Println(src)    dst := hex.EncodeToString(src)    fmt.Println(dst)}游乐场:https://play.golang.org/p/qwT_cGpWoYb输出:Hello Gopher![72 101 108 108 111 32 71 111 112 104 101 114 33]48656c6c6f20476f7068657221
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go