How to transfer hex strings to []byte directly in Go?

huangapple go评论76阅读模式
英文:

How to transfer hex strings to []byte directly in Go?

问题

将字符串"46447381"转换为[]byte{0x46,0x44,0x73,0x81}的方法如下:

package main

import (
	"fmt"
)

func main() {
	str := "46447381"
	bytes := make([]byte, len(str)/2)
	for i := 0; i < len(str); i += 2 {
		fmt.Sscanf(str[i:i+2], "%x", &bytes[i/2])
	}
	fmt.Printf("%v\n", bytes)
}

这段代码使用了fmt.Sscanf函数来将字符串按照16进制格式解析为字节。首先,我们创建了一个长度为字符串长度一半的字节切片bytes。然后,通过循环遍历字符串的每两个字符,并使用fmt.Sscanf将其解析为对应的字节值,存储到bytes切片中。最后,打印输出bytes切片即可得到结果[]byte{0x46,0x44,0x73,0x81}

英文:

Question is simple,

how to transfer &quot;46447381&quot; in to []byte{0x46,0x44,0x73,0x81}?

答案1

得分: 48

只需使用hex.DecodeString()函数:

s := "46447381"

data, err := hex.DecodeString(s)
if err != nil {
    panic(err)
}
fmt.Printf("% x", data)

输出:

46 44 73 81

Go Playground上尝试一下。

注意:

如果只是简单地使用fmt.Println(data)打印字节切片,打印出的值将以十进制格式显示,这就是为什么它与输入的十六进制格式的字符串不匹配的原因。fmt.Println(data)的输出将是:

[70 68 115 129]

这些数字与十进制表示相同。

英文:

Simply use the hex.DecodeString() function:

s := &quot;46447381&quot;

data, err := hex.DecodeString(s)
if err != nil {
    panic(err)
}
fmt.Printf(&quot;% x&quot;, data)

Output:

46 44 73 81

Try it on the Go Playground.

Note:

If you just simply print the byte slice using fmt.Println(data), the printed values will be in decimal format that's why it won't match your input string (because it is specified in hexadecimal format).
Output of fmt.Println(data) would be:

[70 68 115 129]

These are the same numbers just in decimal base.

huangapple
  • 本文由 发表于 2015年2月9日 14:56:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/28404326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定