How to convert a zero-terminated byte array to string?

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

Because not all of the string s are precisely 100 characters 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 a byte array to string in Golang.

1 Like

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)

Refer: stackoverflow.com