go - 在 golang 中将 []uint32 转换为 []byte,反之亦然

标签 go

在 Golang 中将 []uint32 转换为 []byte 的最有效方式(在性能方面)是什么?

例如:

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

我有一个 solution但它由 div、mod 和 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

根据需要为 BigEndian 调整 LittleEndian

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)

}

关于go - 在 golang 中将 []uint32 转换为 []byte,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36429885/

相关文章:

xml - 如何强制 Go 的标准 xml 解析器读取 DTD 实体

unit-testing - 在 golang 模拟依赖项中对 http 处理程序进行单元测试

go - 使用通配符匹配删除 s3 中的对象

mutex - 如何等待低延迟的线程?

dictionary - 在范围循环内从 map 中删除选定的键是否安全?

戈朗 : Ordering map by slice in Go templates

sql - 单值上下文中的多值 .Exec() 与 Golang sql

json - 从 GoLang 中的响应中检索到的漂亮 JSON

windows - 如何在 Windows 上从命令提示符更新 golang?

go - 如何插入 byte slice ?