gpt4 book ai didi

string - 为什么 Go 向我的字符串添加字节?

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

当我在 0x80 或以上的字符串中添加一个字节时,golang 会在我的字节之前添加 0xc2。我认为这与 utf8 runes 有关.无论哪种方式,我如何将 0x80 添加到字符串的末尾?

例子:

var s string = ""
len(s) // this will be 0
s += string(0x80)
len(s) // this will be 2, string is now bytes 0xc2 0x80

最佳答案

来自 specification :

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.

表达式 string(0x80) 的计算结果为 UTF-8 表示形式为 0x80 的字符串,而不是包含单个字节 0x80 的字符串。 0x80的UTF-8表示是0xc2 0x80。

使用\x 十六进制转义来指定字符串中的字节 0x80:

 s += "\x80"

您可以使用 string([]byte) 转换从任意字节序列创建字符串。

 s += string([]byte{0x80})

关于string - 为什么 Go 向我的字符串添加字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673014/

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