Home >Backend Development >Golang >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.
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!