How to Convert a zero terminated byte array to string in Golang?
Here the task is to Convert a zero-terminated byte array to string in Golang, you can use the following method:
1. The string() Function: It is used to convert a zero-terminated byte array to string.
Syntax:
str := string(byteArray[:])
Example:
package main
import (
"fmt"
)
func main() {
arr := [20]byte{ 'a' , 'b' , 'c' , '1' , '2' , '3' }
fmt.Println( "Array: " , arr)
str := string(arr[:])
fmt.Println( "Conversion to string: " , str)
}
|
Output:
Array: [97 98 99 49 50 51 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Conversion to string: abc123
2. The Sprintf() Function: It is also used to convert a zero-terminated byte array to string. But the performance is less than the previous function.
Syntax:
str := fmt.Sprintf("%s", byteArray)
Example:
package main
import (
"fmt"
)
func main() {
arr := [20]byte{ 'a' , 'b' , 'c' , '1' , '2' , '3' }
fmt.Println( "Array: " , arr)
str := fmt.Sprintf( "%s" , arr)
fmt.Println( "Conversion to string: " , str)
}
|
Output:
Array: [97 98 99 49 50 51 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Conversion to string: abc123
Last Updated :
04 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...