简体   繁体   English

将字符串转为 ascii 字节数组

[英]Go string to ascii byte array

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

If you're looking for a conversion, just do byteArray := []byte(myString)如果您正在寻找转换,只需执行byteArray := []byte(myString)

The language spec details conversions between strings and certain types of arrays (byte for bytes, int for Unicode points)语言规范详细说明了字符串和某些类型数组之间的转换(字节表示字节,int 表示 Unicode 点)

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: cthom06 的回答为您提供了一个可以操作的字节切片:

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.但是你提到了ASCII。 If your string is ASCII to begin with, then you are done.如果您的字符串以 ASCII 开头,那么您就完成了。 If it contains something else, you have more to deal with and might want to post another question with more details about your data.如果它包含其他内容,则您需要处理更多内容,并且可能想要发布另一个问题,其中包含有关您的数据的更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM