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

Use:

s := string(byteArray[:])

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)])

This is equivalent to:

s := string(byteArray[:])

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})

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

n := bytes.IndexByte(byteArray[:], 0)

Simplistic solution:

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

I'm not sure how performant this is though.

Tags:

Go