Menu Close

Go – Convert a zero terminated byte array to string in go golang.

In this tutorial, We are going to learn about how to convert a zero terminated byte array to string in go golang.

Example:

byteArray = [10]byte{'a', 'b', 'c', 'd'}

// string function will convert byte array to string
s := string(byteArray[:])

Note: You can’t convert byte array directly to string so first slice it then convert to string.

Example with code:

package main

import (
        "fmt"
)

func main() {

     arr := [10]byte{'a', 'b', 'c'}

     fmt.Println("byte Array: ", arr)

     str := string(arr[:])

     fmt.Println("After converting byte array to string: ", str)
}

Output:

byte Array:  [97 98 99 0 0 0 0 0 0 0]
After converting byte array to string:  abc
package main

import (
        "fmt"
)

func main() {

     arr := [10]byte{'1', '2', '3'}

     fmt.Println("byte Array: ", arr)

     str := string(arr[:])

     fmt.Println("After converting byte array to string: ", str)
}

Output:

byte Array:  [49 50 51 0 0 0 0 0 0 0]
After converting byte array to string: 123

To learn more about golang, You can refer given below link:

https://techieindoor.com/go-lang-tutorial/
https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
Posted in golang

Leave a Reply

Your email address will not be published. Required fields are marked *