How to convert a slice of bytes to []uint16
and reverse without allocation new uint16
slice. This question focused on performance and memory consumption
Asked
Active
Viewed 599 times
0
-
Im currentlu using. But I don't know is it correct: func EncodeUint16(d []byte) []uint16 { return *(*[]uint16)(unsafe.Pointer(&d)) } func EncodeToByteSl(d []uint16) []byte { return *(*[]byte)(unsafe.Pointer(&d)) } – TomX01 Jul 15 '18 at 07:23
1 Answers
0
Consider that converting = copying, except for two special cases: m:=map[string]int{};m[string(bytes))
has no allocation, similarly with append.
Using unsafe.Pointer seems the current workaround (as its name suggests, "unsafe")
u16 := *(*uint16)(unsafe.Pointer(&byte_array[4]))
There is a proposal to use unsafe.Slice
instead.
There is also the (rejected for now) proposal golang/go issue 13656
The problem is having to write
(*[C]T)(unsafe.Pointer(v))[:n:n]
, for some C, T, v, and n.A simpler way to write that entire expression would be ideal.
var s []byte = C.AsSlice((*byte)(ptr), n)