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.
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