Go - What is the best way to convert byte array to string

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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 0s.

If I tansfer [100]byte to string by: string(byteArray[:]), the tailing 0s 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.

Answers

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)

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/14230145/what-is-the-best-way-to-convert-byte-array-to-string

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils