Rabi Siddique
193 words
1 minutes
Bits, Bytes and Byte Slices in Golang
2024-06-13

Bits#

A bit is the smallest unit of data in computing and can have a value of either 0 or 1. Bits are the building blocks of all data in a computer.

Bytes#

A byte is a unit of data that is 8 bits long. It is the basic addressable element in many computer architectures and is used to encode a single character of text in the ASCII encoding system, among other things.

Working with Bytes in Go#

In Go, you often work with bytes when dealing with binary data, file I/O, and network communication. Go provides the byte type, which is an alias for uint8.


package main

import "fmt"

func main() {
    // Defining a byte slice
    data := []byte{72, 101, 108, 108, 111}
    fmt.Println(string(data)) // Output: Hello
}

Byte Slices#

Byte slices ([]byte) are commonly used to represent binary data and mutable strings in Go. They are flexible and powerful for various data manipulation tasks.

package main

import "fmt"

func main() {
    // Creating a byte slice from a string
    str := "Hello"
    byteSlice := []byte(str)

    // Modifying the byte slice
    byteSlice[0] = 'h'
    fmt.Println(string(byteSlice)) // Output: hello
}

Further Reading#

Bits, Bytes and Byte Slices in Golang
https://rabisiddique.com/posts/bits-bytes-in-golang/
Author
Rabi Siddique
Published at
2024-06-13