How to Create a Byte Array in Golang

A byte array in Golang is a fixed-size, ordered collection of elements where each element is a byte. A byte is an 8-bit unsigned integer with a value ranging from 0 to 255. To create a byte in Go, assign an ASCII character to a variable. A byte in Golang is an unsigned 8-bit integer.

Byte arrays are commonly used in programming languages to store and manipulate binary data, like files or network communication, and to represent strings of characters in a more memory-efficient way.

package main

import (
 "fmt"
)

func main() {
 var b1 byte = 65
 var b2 byte = 66

 fmt.Println(b1)
 fmt.Println(b2)
}

Output

65
66

To convert these ASCII numbers to characters, you can use Printf(“%c”) function.

package main

import (
 "fmt"
)

func main() {
 var b1 byte = 65
 var b2 byte = 66

 fmt.Printf("%c\n", b1)
 fmt.Printf("%c\n", b2)
}

Output

A
B

How to Create a byte array in Golang

There are two methods to create a byte array in Go.

  1. Using the []byte type conversion
  2. Using the make() function

Method 1: Using the []byte type conversion

To create a byte array in Golang, you can use a slice of bytes []byte. Golang’s slice data type provides a suitable and efficient way of working with typed data sequences. 

Syntax

[]byte("Your String")

Example

package main

import (
 "fmt"
)

func main() {
 byteArray := []byte{97, 98, 99, 100, 101, 102}
 fmt.Println(byteArray)
}

Output

[97 98 99 100 101 102]

For converting from a string to a byte slice, string -> []byte.

Method 2: Using the make() function

Golang make() is a built-in function used to initialize and allocate memory for slices, maps, and channels.

Syntax

make(Type, length[, capacity])

Example

package main

import "fmt"

func main() {
  byteArray := make([]byte, 5)
  fmt.Println(byteArray)
}

Output

[0 0 0 0 0]

That’s it.

Leave a Comment