"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to efficiently convert strings into byte arrays in Go?

How to efficiently convert strings into byte arrays in Go?

Posted on 2025-04-13
Browse:851

How Can Strings Be Efficiently Converted to Byte Arrays in Go?

Accessing String Values as Bytes

Assigning a string to a byte array allows for low-level data manipulation and manipulation of binary data. One method for achieving this is utilizing a loop to iterate through the range of bytes in the string, assigning each byte to an equivalent index in the byte array.

package main

import (
    "fmt"
)

func main() {
    var arr [20]byte
    str := "abc"

    // Iterate through bytes and assign to byte array
    for k, v := range []byte(str) {
        arr[k] = byte(v)
    }

    // Display the values in the byte array
    fmt.Println(arr)
}

An alternative, more concise and secure approach is to use type conversion:

[]byte("Here is a string....")

This method automatically converts the string into a slice of bytes, eliminating the need for the loop and type conversion in the previous example.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3