英文:
Random byte being added when using string()
问题
我正在尝试对两个值进行异或操作。如果我这样做,我可以得到正确的结果,但是使用string()函数时,结果会随机添加一个字节!有人能解释一下吗?这是一个示例代码的链接:http://play.golang.org/p/tIOOjqo_Fe
英文:
I am attempting to XOR two values. If I do I can get the right result, however, using string() on it results in a random byte being added to it!
Can anyone explain this?
Here's a playground: http://play.golang.org/p/tIOOjqo_Fe
答案1
得分: 7
所以,你有:
z := 175 // 0xaf
这是字符 ¯
的 Unicode 码点。
接下来的代码行将把该值视为 Unicode 码点(rune),并将其转换为 UTF-8 编码的字符串:
out := string(z)
在 UTF-8 编码中,该字符将由两个字节表示:[]byte(0xc2, 0xaf)
因此,你看到的字节是 Go 字符串的 UTF-8 编码。
英文:
So, you have:
z := 175 // 0xaf
That is the unicode code point for the character: ¯
The following line of code will then take the value and treat it as a unicode code point (rune) and turn it into a utf-8 encoded string:
out := string(z)
In utf-8 encoding, that character would be represented by two bytes: []byte(0xc2, 0xaf)
So, the bytes you see are the Go string's utf-8 encoding.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论