How to Convert Byte Array to String in Golang

To convert a byte array to a string in Go, you can use the “string()” constructor, “bytes.NewBuffer()”, or “fmt.Sprintf()” function.

Method 1: Using the string() constructor

The easiest way to convert a byte array to a string in Golang is to use the “string()” constructor. The constructor takes the same bytes as the slice and returns a new string containing that array of bytes.

Syntax

string := string(bytes[:])

Example

A byte in Golang is an unsigned 8-bit integer. A byte has a limit of 0-255 in the numerical range. It represents an ASCII character. Go uses a rune with type int32 to deal with multibyte characters.

package main

import (
 "fmt"
)

func main() {
   bytes := []byte{97, 98, 99, 100, 101, 102}
   str := string(bytes)
   fmt.Println(str)
}

Output

abcdef

To format and print the output in the console, import the fmt package in Go.

To assign a byte in Golang, use the []byte{} syntax.

Then, convert a byte into a string bypassing bytes to the string() method.

Using fmt.Println() method, we printed the string on the console.

Method 2: Using the bytes.NewBuffer() package

Go provides a package called bytes with a function called NewBuffer(), which creates a new Buffer and then uses the String() method to get the string output.

Syntax

bytes.NewBuffer(buf)

Example

package main

import (
 "bytes"
 "fmt"
)

func main() {
   byteArray := []byte{97, 98, 99, 100, 101, 102}
   str := bytes.NewBuffer(byteArray).String()
   fmt.Println(str)
}

Output

abcdef

In this example, we defined a byteArray and then passed that byteArray to the NewBuffer() function, then converted its output object to a string by calling the String() method on that object.

You can see that it returns a string converted from a bytes array. It is the same output as the above section.

Method 3: Using fmt.Sprintf() function

The fmt.Sprintf() method formats according to a format specifier and returns the resulting string. You can use Sprintf() function to convert an array of bytes to a string.

The fmt.Sprintf() method is slow, but we can convert byte array to string.

Example

package main

import (
 "fmt"
)

func main() {
 byteArray := []byte{97, 98, 99, 100, 101, 102}
 str := fmt.Sprintf("%s", byteArray)
 fmt.Println(str)
}

Output

abcdef

That’s it.

See also

Go int to string

Golang Itoa()

Golang FormatInt()

Leave a Comment