在golang中将[] uint32转换为[]字节,反之亦然 [英] Convert []uint32 to []byte and vice versa in golang

查看:253
本文介绍了在golang中将[] uint32转换为[]字节,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[] uint32 转换为 [] byte 的最有效方式Golang?

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
   // ?
}

我有一个解决方案,但它包含div,mod和multiply

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)
}


推荐答案

我怀疑你是在类似这样的 Playground

I suspect you are after something like this Playground

为<$ $调整 LittleEndian c $ c> BigEndian 视情况而定

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)

}

这篇关于在golang中将[] uint32转换为[]字节,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆