I need to convert an array of strings to an array of byte arrays. This code works, but the repeated append
seems distasteful to me. Is there a better way?
input := []string{"foo", "bar"}
output := [][]byte{}
for _, str := range input {
output = append(output, []byte(str))
}
fmt.Println(output) // [[102 111 111] [98 97 114]]
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.
One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.
In Java, the string literals are stored as an array of Unicode characters. A byte array is an array of bytes. We can use a byte array to store the collection of binary data.
No matter what, you will need to create a new [][]byte
and loop over the []string
. I would avoid using append by using the following code, but it is really all a question of style. Your code is perfectly correct.
input := []string{"foo", "bar"}
output := make([][]byte, len(input))
for i, v := range input {
output[i] = []byte(v)
}
fmt.Println(output) // [[102 111 111] [98 97 114]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With