I want to assign string to bytes array:
var arr [20]byte
str := \"abc\"
for k, v := range []byte(str) {
arr[k] = byte(v)
}
Have another m
You need a fast way to convert a []string to []byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in []byte type.
package main
func main() {
var s string
//...
b := []byte(s)
//...
}
which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:
WriteFile func(filename string, data []byte, perm os.FileMode) error
Another example
package main
import (
"fmt"
"strings"
)
func main() {
stringSlice := []string{"hello", "world"}
stringByte := strings.Join(stringSlice, " ")
// Byte array value
fmt.Println([]byte(stringByte))
// Corresponding string value
fmt.Println(string([]byte(stringByte)))
}
Output:
[104 101 108 108 111 32 119 111 114 108 100] hello world
Please check the link playground
Safe and simple:
[]byte("Here is a string....")
Arrays are values... slices are more like pointers. That is [n]type
is not compatible with []type
as they are fundamentally two different things. You can get a slice that points to an array by using arr[:]
which returns a slice that has arr
as it's backing storage.
One way to convert a slice of for example []byte
to [20]byte
is to actually allocate a [20]byte
which you can do by using var [20]byte
(as it's a value... no make
needed) and then copy data into it:
buf := make([]byte, 10)
var arr [10]byte
copy(arr[:], buf)
Essentially what a lot of other answers get wrong is that []type
is NOT an array.
[n]T
and []T
are completely different things!
When using reflect []T
is not of kind Array but of kind Slice and [n]T
is of kind Array.
You also can't use map[[]byte]T
but you can use map[[n]byte]T
.
This can sometimes be cumbersome because a lot of functions operate for example on []byte
whereas some functions return [n]byte
(most notably the hash functions in crypto/*
).
A sha256 hash for example is [32]byte
and not []byte
so when beginners try to write it to a file for example:
sum := sha256.Sum256(data)
w.Write(sum)
they will get an error. The correct way of is to use
w.Write(sum[:])
However, what is it that you want? Just accessing the string bytewise? You can easily convert a string
to []byte
using:
bytes := []byte(str)
but this isn't an array, it's a slice. Also, byte
!= rune
. In case you want to operate on "characters" you need to use rune
... not byte
.
For example,
package main
import "fmt"
func main() {
s := "abc"
var a [20]byte
copy(a[:], s)
fmt.Println("s:", []byte(s), "a:", a)
}
Output:
s: [97 98 99] a: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
I think it's better..
package main
import "fmt"
func main() {
str := "abc"
mySlice := []byte(str)
fmt.Printf("%v -> '%s'",mySlice,mySlice )
}
Check here: http://play.golang.org/p/vpnAWHZZk7
Besides the methods mentioned above, you can also do a trick as
s := "hello"
b := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))
Go Play: http://play.golang.org/p/xASsiSpQmC
You should never use this :-)