2 Ways to Convert Golang String to Byte Array

Go byte is an unsigned 8-bit integer with an uint8 data type.

To convert the byte array to a string, use the string() constructor.

What is String in Go?

Golang string is a sequence of variable characters where each character is represented by one or more bytes using UTF-8 Encoding.

A byte in Golang is an unsigned 8-bit integer.

A Golang byte is an unsigned 8-bit integer, and a bytearray is an array of characters.

What is a byte array in Go?

A byte array in Golang is an area of memory containing a cluster of contiguous bytes in a way that makes sense to talk about them in order. A byte array is a consecutive sequence of variables of the data type.

Why would you convert a string to a byte array?

We need to convert a string to a byte array in Golang because bytes are very common when working with slices.

The byte() function returns a slice with all the bytes of the characters in the specified string.

Golang String to Byte Array

Golang has two ways to convert a string to a byte array.

  1. Using []byte(): It returns a new byte slice containing the same bytes.
  2. Using []rune(): It converts a string into a range of Unicode code points representing runes.

Method 1: Using []byte()

To convert string to byte array in Golang, use the []byte(). It will create a new byte slice that contains the same bytes as the string.

Syntax

[]byte(string)

Example

package main

import (
 "fmt"
)

func main() {
   bt := []byte("kb")
   fmt.Println(bt)
}

Output

[107  98]

You can see that it returns the array of bytes. In addition, it returns the ASCII values of the letter k and b, which is 107 and 98, respectively.

Converting special characters string to bytes

To convert special characters strings to bytes in Go, use the []byte(). This is because so many special characters can create a string.

package main

import (
 "fmt"
)

func main() {
   bt := []byte("{}@#$+-=[]\\|;':\",./<>?")
   fmt.Println(bt)
}

Output

[123 125 64 35 36 43 45 61 91 93 92 124 59 39 58 34 44 46 47 60 62 63]

Method 2: Using []rune()

To convert a string into a range of Unicode code points representing runes, you can use the []rune() method.

package main

import (
  "fmt"
)

func main() {
  str := "kb"
  runes := []rune(str)
  fmt.Println(runes)
}

Output

[107 98]

The above code will generate a slice of runes containing the same characters as the string, regardless of the number of bytes required to represent each character.

A new duplicate of the data will be created when a string is converted to a byte slice or a slice of runes. Therefore, changing the slice will not impact the original string.

That’s it for this tutorial.

Leave a Comment