Given an string array which only contains single characters such as:
ex := [...]string{"a","o",".",".","2",".",".","9"}
is there a way to get a byte array with same content but with bytes instead of strings?
CodePudding user response:
Use a conversion to convert each string
to a []byte
.
ex := [...]string{"a", "o", ".", ".", "2", ".", ".", "9"}
var ey [len(ex)][]byte
for i := range ex {
ey[i] = []byte(ex[i])
}
Use this code if your intent is to get a byte array of the joined strings. This code only works when the strings are single ASCII characters.
ex := [...]string{"a", "o", ".", ".", "2", ".", ".", "9"}
var ey [len(ex)]byte
for i := range ex {
ey[i] = ex[i][0]
}
Use this expression of you want to get a slice of bytes of the joined strings: []byte(strings.Join(ex[:], ""))
I don't know the your context for doing this, but my guess is that it's more appropriate to use a slice than an array:
ex := []string{"a", "o", ".", ".", "2", ".", ".", "9"}
ey := make([][]byte, len(ex))
for i := range ex {
ey[i] = []byte(ex[i])
}
..
s := []byte(strings.Join(ex, ""))
CodePudding user response:
This seems to do it:
package main
import (
"fmt"
"strings"
)
func main() {
a := [...]string{"a","o",".",".","2",".",".","9"}
var b [len(a)]byte
c := strings.Join(a[:], "")
copy(b[:], c)
// [8]uint8{0x61, 0x6f, 0x2e, 0x2e, 0x32, 0x2e, 0x2e, 0x39}
fmt.Printf("%#v\n", b)
}
https://godocs.io/strings#Join
CodePudding user response:
Depending on if this is part of a code-generation pipeline, you can do this a couple of ways.
Directly:
bs := [...]byte{'a', 'o', '.', '.', '2', '.', '.', '9'}
or indirectly:
ex := [...]string{"a", "o", ".", ".", "2", ".", ".", "9"}
bs := [...]byte{
ex[0][0],
ex[1][0],
ex[2][0],
ex[3][0],
ex[4][0],
ex[5][0],
ex[6][0],
ex[7][0],
} // type [8]int8 i.e. [8]byte
https://play.golang.org/p/iMEjFpCKAaW
Depending on your use case, these ways may be too rigid. For dynamic initialization methods see the other answers here.