问题描述
我需要读取[100]byte
来传输一堆string
数据.
I need to read [100]byte
to transfer a bunch of string
data.
由于并非所有string
的长度都恰好是100个字符,因此byte array
的其余部分将填充0
s.
Because not all of the string
s are precisely 100 characters long, the remaining part of the byte array
is padded with 0
s.
如果通过以下方式将[100]byte
转换为string
:string(byteArray[:])
,则尾部0
将显示为^@^@
s.
If I convert [100]byte
to string
by: string(byteArray[:])
, the tailing 0
s are displayed as ^@^@
s.
在C中,string
将在0
处终止,那么在Go中将此byte array
转换为string
的最佳方法是什么?
In C, the string
will terminate upon 0
, so what's the best way to convert this byte array
to string
in Go?
推荐答案
将数据读取到字节片中的方法返回读取的字节数.您应该保存该数字,然后使用它来创建您的字符串.如果n
是读取的字节数,则代码将如下所示:
Methods that read data into byte slices return the number of bytes read. You should save that number and then use it to create your string. If n
is the number of bytes read, your code would look like this:
s := string(byteArray[:n])
要转换完整的字符串,可以使用:
To convert the full string, this can be used:
s := string(byteArray[:len(byteArray)])
这等效于:
s := string(byteArray)
如果由于某些原因您不知道n
,则可以使用bytes
包来查找它,前提是您的输入中没有嵌入空字符.
If for some reason you don't know n
, you could use the bytes
package to find it, assuming your input doesn't have a null character embedded in it.
n := bytes.Index(byteArray, []byte{0})
或者像icza所指出的那样,您可以使用以下代码:
Or as icza pointed out, you can use the code below:
n := bytes.IndexByte(byteArray, 0)
这篇关于如何将零结尾的字节数组转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!