What is the best way to convert byte array to string?

I need to read [100]byte to transfer a bunch of string data.

Because not all the string is precisely 100 long, the remaining part of the byte array are padded with 0 s.

If I tansfer [100]byte to string by: string(byteArray[:]) , the tailing 0 s are displayed as ^@^@ s.

In C the string will terminate upon 0 , so I wonder what's the best way of smartly transfer byte array to string .


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. n being the number of bytes read, your code would look like this:

s := string(byteArray[:n])

If for some reason you don't have n , you could use the bytes package to find it, assuming your input doesn't have a null character in it.

n := bytes.Index(byteArray, []byte{0})

Or as icza pointed out, you can use the code below:

n := bytes.IndexByte(byteArray, 0)

关于什么?

s := string(byteArray[:])

Simplistic solution:

str := fmt.Sprintf("%s", byteArray)

I'm not sure how performant this is though.

链接地址: http://www.djcxy.com/p/87212.html

上一篇: TypeError:必须是不带空字节的字符串,而不是os.system()中的str

下一篇: 将字节数组转换为字符串的最佳方法是什么?