go - 在go中将字符串转换为字节

标签 go byte

基本上,我想做的是将十六进制格式的字符串转换为字节,然后将该字节附加到 byte slice 上。

我试过了:

func main() {
    bytes := []byte{0xfc}
    string := "0xe8"
    bytes = append(bytes, string...)
    fmt.Printf("%s", bytes)
}

输出:
�0xe8

我知道我可以声明一个字节变量并附加该字节。
我需要将字符串转换为字节。

预期产量:
��

最佳答案

这对我来说是工作。

func main() {
    bytes := []byte{0xfc}
    str := "0xe8"
    pc, _ := strconv.ParseUint(str, 0, 64)

    bytes = append(bytes, uint8(pc))
    fmt.Printf("%s", bytes)
}
输出:
��

关于go - 在go中将字符串转换为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59224937/

相关文章:

C++ libCurl : Post callback function to send more than one byte

c - 为什么要添加填充,如果 char 在 int 之后?

c# - 使用字节访问位图内存信息

GO:导入我的 go 文件时出错

go - 什么是 channel 缓冲区大小?

温暖 worker 的Go worker 模式

java - 如何将 Int 转换为无符号字节并返回

测试时Golang "plugin was built with a different version of package"

sockets - Go:从套接字读取时出现意外的 EOF

java - 使用 Cp500(LF 和 NEL)编码陌生度