Open In App

How to Convert a zero terminated byte array to string in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

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:




// Go program to illustrate how to 
// convert a zero terminated byte
// array to string.
   
package main
   
import (
        "fmt"
)
   
func main() {
       
       
    // zero terminated byte
    // array
     arr := [20]byte{'a', 'b', 'c' , '1', '2', '3'}
        
    // printing the array
     fmt.Println("Array: ", arr)
        
     // convert a zero terminated
     // byte array to string
     // using string() method
     str := string(arr[:])
        
     // printing the converting
     // string
     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:




// Go program to illustrate how to 
// convert a zero terminated byte
// array to string.
   
package main
   
import (
        "fmt"
)
   
func main() {
       
       
    // zero terminated byte
    // array
     arr := [20]byte{'a', 'b', 'c' , '1', '2', '3'}
        
    // printing the array
     fmt.Println("Array: ", arr)
        
     // convert a zero terminated
     // byte array to string
     // using Sprintf() method
     str := fmt.Sprintf("%s", arr)
        
     // printing the converting
     // string
     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
Previous
Next
Share your thoughts in the comments
Similar Reads