Skip to content
Related Articles

Related Articles

How to Convert a zero terminated byte array to string in Golang?
  • Last Updated : 04 May, 2020

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
Recommended Articles
Page :