将Go字符串转换为ASCII字节数组

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

Go string to ascii byte array

问题

如何将我的字符串编码为ASCII字节数组?

英文:

How can I encode my string as ASCII byte array?

答案1

得分: 118

如果您正在寻找一种转换,只需执行<code>byteArray := []byte(myString)</code>

语言规范详细说明了字符串与某些类型的数组(字节用于字节,整数用于Unicode点)之间的转换。

英文:

If you're looking for a conversion, just do <code>byteArray := []byte(myString)</code>

The language spec details conversions between strings and certain types of arrays (byte for bytes, int for Unicode points)

答案2

得分: 8

你可能不需要做任何事情。如果你只需要读取字符串的字节,你可以直接这样做:

c := s[3]

cthom06的回答给出了一个你可以操作的字节切片:

b := []byte(s)
b[3] = c

然后,如果你愿意,你可以从修改后的字节切片创建一个新的字符串:

s = string(b)

但是你提到了ASCII。如果你的字符串一开始就是ASCII的,那么你已经完成了。如果它包含其他内容,你还需要处理更多的事情,可能需要发布另一个带有关于你的数据更多细节的问题。

英文:

You may not need to do anything. If you only need to read bytes of a string, you can do that directly:

c := s[3]

cthom06's answer gives you a byte slice you can manipulate:

b := []byte(s)
b[3] = c

Then you can create a new string from the modified byte slice if you like:

s = string(b)

But you mentioned ASCII. If your string is ASCII to begin with, then you are done. If it contains something else, you have more to deal with and might want to post another question with more details about your data.

huangapple
  • 本文由 发表于 2010年7月30日 21:10:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/3371714.html
匿名

发表评论

匿名网友

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

确定