vue

How to convert byte array to string in Golang


In this article, you will learn about how to convert a byte array to a string in the Go language.

In Go language, strings are nothing but a combination of an array of bytes. You can convert a string into a bytes array, similarly, you can convert a byte array into a string. In this article, we will explore how you can convert a byte array into a string. There are a bunch of ways to do it. Let’s see them in the below section with examples.

You may convert a byte array to a string by using a slice and it is the easiest way to do so. Let’s see the below code example where we are converting a byte array of “Good Morning!” into a string.

import (
        "fmt"
)

func main() {
        bytesOfArray := []byte{71, 111, 111, 100, 32, 77, 111, 114, 110, 105, 110, 103, 33}
        str := string(bytesOfArray[:])
        fmt.Println("Converting into String =", str)
}

// Output: Converting into String = Good Morning!

You can see that we are getting the specific string from the bytes of the array. There’s another way to perform this action.

You may use the bytes package to perform this action. To do so you need to import the bytes package and with the help of this package, you may convert a bytes array into a string. Let’s see the below code example. Here we will convert a bytes array of “Hello World!” into the string.

package main

import (
        "bytes"
        "fmt"
)

func main() {
        bytesOfArray := []byte{72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33}
        str := bytes.NewBuffer(bytesOfArray).String()
        fmt.Println("Converting into String =", str)
}

// Output: Converting into String = Hello World!

Here, we import the bytes package and with the help of it we convert a bytes array into a specific string.

There’s another way to convert a bytes array into a string and that is using Sprintf() function. For example, we will convert a bytes array of “Good Evening!” into a string by using Sprintf() function. See the example code below:

package main

import (
        "fmt"
)

func main() {
        bytesOfArray := []byte{71, 111, 111, 100, 32, 69, 118, 101, 110, 105, 110, 103, 33}
        str := fmt.Sprintf("%s", bytesOfArray)
        fmt.Println("Converting into String =", str)
}

// Output: Converting into String = Good Evening!

These are the ways of converting a byte array into a string. You may use these methods to convert your own bytes array into strings. You may also use single characters instead of using bytes and these functions will work the same.


Share on social media

//