AppDividend
Latest Code Tutorials

How to Convert Golang String to Byte Array

In Golang, to convert a string to a byte array, you get a slice that contains the bytes of the string. In Go, a string is, in effect, a read-only slice of bytes. It’s essential to state right up front that a string holds arbitrary bytes. It is not required to hold Unicode text, UTF-8 text, or any other predefined format. As far as the content of a string is concerned, it is precisely equivalent to a slice of bytes.

Convert String to Byte Array

To convert String to Byte array in Golang, use the byte() function. A byte is an 8-bit unsigned int. In Golang, we often use byte slices. The byte() function takes a string as an input and returns the array.

Here is a Go example that shows how to convert a string to a byte array.

package main

import "fmt"

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

Output

go run hello.go
[77 66 66 36]

In the code, first, we have defined string MBB$ and then convert that string into a slice of bytes.

Then use the fmt.Println() method to print the array of bytes.

Golang bytes.Index()

Here we import the “bytes” package at the top (in the import statement). We call bytes.Index() to locate the sequence with the byte values.

See the following code.

// hello.go

package main

import (
	"bytes"
	"fmt"
)

func main() {
	values := []byte("Pug")

	// Search for this byte sequence.
	result := bytes.Index(values, []byte("g"))
	fmt.Println(result)

	// This byte sequence is not found.
	result = bytes.Index(values, []byte("Dog"))
	if result == -1 {
		fmt.Println("Dog not found")
	}
}

Output

go run hello.go
2
Dog not found

Golang strings.Index() method, bytes.Index() function returns the index if a sequence matches. Otherwise, it returns -1.

In the first example, we find g matches with Pug, so it returns the index of g in Pug, which is 2 because the index starts with 0.

In the second example, we don’t find the Dog sequence in Pug; that is why it returns Dog not found.

Golang Copy string to a byte slice

Golang copy() is an inbuilt method that can copy the string into a byte slice.

See the following code.

// hello.go

package main

import "fmt"

func main() {
	// Create an empty byte slice of length 4.
	values := make([]byte, 4)
	// Copy string into bytes.
	animal := "pug"
	copied := copy(values, animal)
	fmt.Println(copied)
	fmt.Println(values)
}

Output

go run hello.go
3
[112 117 103 0]

Here we create an empty 4-element byte slice. Then we copy a three-element string into it.

See also

Golang json to map

Golang slice to string

Golang int to string

Leave A Reply

Your email address will not be published.

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