How to Convert Byte Array to String in Go

Created
Modified

Using string Function

The easiest way to convert []byte to string in Golang:

package main

import "fmt"

func main() {
  b := []byte{'a', 'b', 'c'}

  s := string(b[:])
  fmt.Printf("%q\n", s)
}
"abc"

Using fmt.Sprintf Function

You can use fmt.Sprintf function to convert byte array to string. The following example:

package main

import "fmt"

func main() {
  b := []byte{'a', 'b', 'c'}

  s := fmt.Sprintf("%s", b)
  fmt.Printf("%q\n", s)
}
"abc"

a zero-terminated byte array

If you want to convert a zero-terminated byte array to string. See the following example:

package main

import (
  "bytes"
  "fmt"
)

func main() {
  b := [5]byte{'a', 'b', 'c'}

  s := string(b[:])
  fmt.Printf("%q length:[%d]\n", s, len(s))

  // remove zero-terminated byte
  n := bytes.Index(b[:], []byte{0})
  s = string(b[:n])
  fmt.Printf("%q length:[%d]\n", s, len(s))
}
"abc\x00\x00" length:[5]
"abc" length:[3]

Related Tags