How to Convert String to Byte Array in Golang

If you want to convert the byte array to string in Go, use the string() constructor.

Golang String to Byte Array

To convert string to byte array in Go, 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

There are so many special characters that can create a string. Let’s covert these characters to bytes.

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]

That’s it for this tutorial.

See also

How to Create a byte array

Golang Atoi()

Golang Itoa()

Leave a Comment