How to Convert Zero Terminated Byte Array to String in Golang

To convert a zero-terminated byte array to a string in Golang, you can use the bytes.IndexByte() function to find the index of the terminating zero bytes (0x00) in the byte array, and then use the string() function to convert the byte array to a string up to that index.

Example

package main

import (
  "bytes"
  "fmt"
)

func main() {
  byteArray := []byte{72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 0}
  index := bytes.IndexByte(byteArray, 0)
  str := string(byteArray[:index])
  fmt.Println(str)
}

Output

Hello, World

In this example, the bytes.IndexByte() function is called with the byte array and the terminating zero bytes as its arguments. The function returns the index of the terminating zero bytes in the byte array.

The string() function converts the byte array to a string up to the index of the terminating zero bytes. Finally, the resulting string is printed to the console.

Note that the bytes.IndexByte() function returns -1 if the terminating zero bytes are not found in the byte array. You should check for this case and handle it appropriately.

Using the bytes.Index() method

You can also use the bytes.Index() function to find the index of the ‘zero’ character and slice the byte array consequently.

Example

package main

import (
  "bytes"
  "fmt"
)

func main() {
  byteArray := []byte{72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 0}
  index := bytes.Index(byteArray[:], []byte{0})
  str := string(byteArray[:index])
  fmt.Println(str)
}

Output

Hello, World

Using the fmt.Sprintf() function

The fmt.Sprintf() function is another way to convert a zero-terminated byte array to a string in Go. It takes a format specifier and returns the resulting string.

Example

package main

import (
  "fmt"
)

func main() {
  byteArray := []byte{72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 0}
  str := fmt.Sprintf("%s", byteArray)
  fmt.Println(str)
}

Output

Hello, World

However, the Sprintf() function performs less than the string() function.

That’s it.

Leave a Comment