首页 > 解决方案 > 如何在 Golang 中使用位打包将结构编码为二进制

问题描述

我正在尝试将大型数据结构编码为二进制。我为每个结构元素指定了位数。所以我需要根据位长将结构编码为二进制。标准 Golang 库编码/二进制将每个项目最小打包为一个字节。因此我需要另一种解决方案。如何在 Go 中将 struct 元素编码为指定的位数?

例如; Item1 = 00001101 Item2 = 00000110 结果为 01101110

type Elements struct{
    Item1 uint8  // number of bits = 5
    Item2 uint8  // number of bits = 3
    Item3 uint8  // number of bits = 2
    Item4 uint64 // number of bits = 60
    Item5 uint16 // number of bits = 11
    Item6 []byte // bit length = 8
    Item7 Others
}
type Others struct{
    Other1 uint8  // number of bits = 4
    Other2 uint32 // number of bits = 21
    Other3 uint16 // number of bits = 9
}

标签: gostructencodingbinarybit-packing

解决方案


推荐阅读