How to Convert Byte Array to String in Golang

Here are three ways to convert byte array to string in Go.

  1. Using string() constructor
  2. Using bytes.NewBuffer()
  3. Using fmt.Sprintf()

Convert Byte Array to String in Go

Method 1: Using the string() constructor

The string constructor takes the same bytes as the slice and returns a new string containing that byte arrays.

Using the string() constructor

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

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.

Using the bytes.NewBuffer() package

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

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.

Using fmt.Sprintf() function

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

Which method is the best and why: Table Comparison

Method Result Example Advantages Disadvantages
string() constructor "Hello, AI!" Simplest and most direct method. None.
bytes.NewBuffer() "Hello, AI!" It is helpful when you have other buffer-related operations. Slightly more verbose for just conversion.
fmt.Sprintf() "Hello, AI!" Provides flexibility with formatting. The overhead of using a formatting function.

Related posts

Go int to string

Golang Itoa()

Golang FormatInt()