Skip to main content
Go

Convert String to Bytes in Go

This simple tutorial shows you two ways of converting a string into bytes in golang with practical but simple examples.

LHB Community

Warp Terminal

Strings in Go are essentially the same as immutable byte slice; hence they can be easily typecasted into each other based on the requirements.

Let's see some ways to perform this conversion:

Using the byte() function

This uses the following syntax.

byteArray = []byte(str)

We get a byte slice as the returned value on using this function. The byteArray stores an 8-bit unicode or ASCII values for each character in the string.

Let's take an example to see this in action:

// main.go
package main

import "fmt"

func main() {
  s := "Hello World!"
  byteArray := []byte(s)
  fmt.Println(byteArray)
}

Running the program:

go run main.go
Convert string to bytes using Byte function in Go

Observing the output, you can see that for each character, the respective ASCII character is stored in the byte array.

Using the copy() function

Another way to convert strings to a byte array is to run the copy function.
It follows the syntax:

copyCount := copy(byteArray, str)

copyCount represents the number of characters copied which is the lower of the lengths of str and the byteArray.

Let's take an example to demonstrate the copy function:

// main.go
package main

import "fmt"

func main() {
  str := "Hello World!"

  // Create a destination byte array with the same length as the string
  byteArray := make([]byte, len(str))

  // Copy bytes from the string to the byte array
  copied := copy(dst, str)

  // Print the copied bytes and the resulting byte array
  fmt.Println("Copied bytes:", copied, "byteArray:", byteArray)
}

Now, let's run this program:

go run main.go
Convert string to bytes using  Copy function in Go

We see that 12 bytes are copied, which is equal to the length of the string and the byteArray stores the individual ASCII characters.

Why do we need byte slices?

Data is often represented and stored as bytes instead of plain strings. Some common scenarios include:

  • Binary file I/O - Reading/Writing to files using byte slices help to efficiently handle the binary data.
  • Network transmissions - HTTP and network data need to be serialized into binary format before being transmitted over some networking media. Interoperability between strings and byte slices allow ease of this serializability.

Let's take an example depicting this use case:

// main.go
package main

import (
  "fmt"
  "os"
)

func main() {
  str := "Hello World!"

  // Convert string to byte slice
  byteArray := []byte(str)

  err := os.WriteFile("out.txt", byteArray, 0644)
  if err != nil {
    fmt.Println("Error writing to file:", err)
    return
  }

  fmt.Println("Write to file successful!")
}

Executing the program:

go run main.go
cat out.txt
Convert string to bytes

Conclusion

In this tutorial, I covered two ways of converting strings to byte slices in Go.

Using the byte() function initializes and returns a new byte slice with the size equal to the size of the string.

Using the copy() function copies the individual string bytes to an existing array and returns the number of bytes copied.

Data is often persisted and transmitted in binary format rather than strings, hence the interoperability between strings and byte slices help perform these conversions efficiently. However, care must be taken using these functions since the entire string is deep copied and repeated use may increase the program memory utilization and runtimes.

✍️
Madhur Batra is an experienced DevOps engineer who likes to share his learnings and experience with the community.
LHB Community