Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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

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

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

In C, the string will terminate upon 0, so what's the best way to convert this byte array to string in Go?

like image 876
Derrick Zhang Avatar asked Jan 09 '13 07:01

Derrick Zhang


People also ask

Can we convert byte to string in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

How does Java convert byte array to string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can we convert byte array to file in Java?

In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.


2 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. 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) 
like image 74
Daniel Avatar answered Sep 21 '22 16:09

Daniel


Use:

s := string(byteArray[:]) 
like image 39
mattes Avatar answered Sep 25 '22 16:09

mattes