Home > Backend Development > Golang > How Can Strings Be Efficiently Converted to Byte Arrays in Go?

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

DDD
Release: 2024-12-11 03:13:10
Original
542 people have browsed it

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)
}
Copy after login

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

[]byte("Here is a string....")
Copy after login

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

The above is the detailed content of How Can Strings Be Efficiently Converted to Byte Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template