gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:35 26 4
gpt4 key购买 nike

请原谅我对这门语言的陌生。我找到了这个编码为字节的示例,然后它使用 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 以便稍后在代码中使用,而不是将其打印出来。


编辑原始问题被标记为与此重复:Format a Go string without printing?

但是,那里的答案似乎只涉及使用 Sprintf 格式化字符串,在这个问题中,我试图弄清楚如何格式化 hex它是从 byte 编码的,但示例是使用 %sfmt.Printf 中打印出来的。但我想格式化以在一个变量中使用,该变量可以在后面部分的代码中重用。所以我不认为这是标记原因的重复,因为它涉及格式化字符串,而不是字节的十六进制


最佳答案

例如,

package main

import (
"encoding/hex"
"fmt"
)

func main() {
str := "Hello Gopher!"
fmt.Println(str)
src := []byte(str)
fmt.Println(src)
dst := hex.EncodeToString(src)
fmt.Println(dst)
}

Playground :https://play.golang.org/p/qwT_cGpWoYb

输出:

Hello Gopher!
[72 101 108 108 111 32 71 111 112 104 101 114 33]
48656c6c6f20476f7068657221

关于go - 设置 %s 从字节编码的十六进制到变量 golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54084576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com