How to Convert Byte Array to String in Golang

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. Golang uses rune, which has type int32 in which you can deal with multibyte characters.

Golang byte array to string

To convert the byte array to string in Golang, use the string() constructor. The string() constructor takes the same bytes as the slice and returns a new string containing that array of bytes.

Syntax

string := string(bytes[:])

Example

package main

import (
 "fmt"
)

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

Output

abcdef

To work 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.

Converting byte array to string using bytes package

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

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 and 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.

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.

package main

import (
 "fmt"
)

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

Output

abcdef

Conclusion

In Golang, converting a byte array (UTF-8) to a string by doing string(bytes), it should be a string(byte[:n]) assuming byte is a slice of bytes. That’s it for this tutorial.

See also

Go int to string

Golang Itoa()

Golang FormatInt()

Leave a Comment