How to Convert Golang String to Byte Array

0
19348
Golang - How To Convert String to Byte Array Example

In Golang, you get a slice containing the string’s bytes to convert a string to a byte array. In Go, a string is, in effect, a read-only slice of bytes. Therefore, it’s essential to state that a string holds arbitrary bytes.

A byte is an 8-bit unsigned int.

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. In Golang, we often use byte slices.

Golang String to Byte Array

To convert string to byte array in Golang, use the byte() function. The byte() function takes a string as input and returns the 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 defined the string MBB$ and then converted 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 Pug, so it returns the index of g in Pug, which is two 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 a built-in method to 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.

That’s it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

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