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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.