How to Convert a String to Byte Array in Go

To convert a string to a byte array in Go, you can use the []byte() function.

Syntax

[]byte(input_string)

Parameters

input_string: We pass a string to the byte slice.

Return value

It returns the bytes of all the characters of the string.

Example 1: Usage of []byte()

Usage of []byte()

package main

import "fmt"

func main() {
  str := "MBB$"
  bt_arr := []byte(str)
  fmt.Println(bt_arr)
}

Output

[77 66 66 36]

Example 2: Converting a string to a range of unicode code points

Converting a string to a range of unicode code points

package main

import (
  "fmt"
)

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

Output

[107 98]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.