Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert []uint32 to []byte and vice versa in golang

Tags:

go

What's the most efficient way (in performance) to convert []uint32 to and from []byte in Golang?

for example:

func main() {
   source := []uint32{1,2,3}
   dest := make([]byte, 4 * len(source))
   // source to dest
   // ?
   check := len(dest)/4
   // dest to check
   // ?
}

I have a solution but it consist div, mod, and multiply

package main
import (
    "fmt"
)
func main() {
    source := []uint32{1,2,3}
    dest := make([]byte, 4*len(source))
    fmt.Println(source)
    for start, v := range source {
       dest[start*4+0] = byte(v % 256)
       dest[start*4+1] = byte(v / 256 % 256)
       dest[start*4+2] = byte(v / 256 / 256 % 256)
       dest[start*4+3] = byte(v / 256/ 256/ 256% 256)
    }
    fmt.Println(dest)
    check := make([]uint32,cap(dest)/4)
    for start := 0; start<len(check); start++ {
       check[start] = uint32(dest[start*4+0]) + uint32(dest[start*4+1]) * 256 + uint32(dest[start*4+2]) * 256 * 256 + uint32(dest[start*4+3]) * 256 * 256 * 256
    }  
    fmt.Println(check)
}
like image 709
Kokizzu Avatar asked Apr 05 '16 14:04

Kokizzu


1 Answers

I suspect you are after something like this Playground

Adjust LittleEndian for BigEndian as appropriate

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

func main() {
    buf := new(bytes.Buffer)
    source := []uint32{1, 2, 3}
    err := binary.Write(buf, binary.LittleEndian, source)
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    fmt.Printf("Encoded: % x\n", buf.Bytes())

    check := make([]uint32, 3)
    rbuf := bytes.NewReader(buf.Bytes())
    err = binary.Read(rbuf, binary.LittleEndian, &check)
    if err != nil {
        fmt.Println("binary.Read failed:", err)
    }
    fmt.Printf("Decoded: %v\n", check)

}
like image 185
Nick Craig-Wood Avatar answered Nov 09 '22 09:11

Nick Craig-Wood