Is it safe to cast binary data from a byte array to a string and back in golang?

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

Is it safe to cast binary data from a byte array to a string and back in golang?

问题

也许是一个愚蠢的问题,但如果我有一些任意的二进制数据,我可以将其转换为字符串,然后再转回字节数组而不损坏数据吗?

[]byte(string(byte_array)) 是否总是等同于 byte_array

英文:

Maybe a stupid question, but if I have some arbitrary binary data, can I cast it to string and back to byte array without corrupting it?

Is []byte(string(byte_array)) always the same as byte_array?

答案1

得分: 3

表达式 []byte(string(byte_slice)) 的求值结果是一个与 byte_slice 长度和内容相同的切片。这两个切片的容量可能不同。

尽管某些语言特性假设字符串包含有效的 UTF-8 编码文本,但字符串可以包含任意字节。

英文:

The expression []byte(string(byte_slice)) evaluates to a slice with the same length and contents as byte_slice. The capacity of the two slices may be different.

Although some language features assume that strings contain valid UTF-8 encoded text, a string can contain arbitrary bytes.

huangapple
  • 本文由 发表于 2015年9月23日 08:12:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/32729036.html
匿名

发表评论

匿名网友

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

确定