如何在 Golang 中使用位打包将结构编码为二进制

问题描述 投票:0回答:1

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

例如; 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
}
go struct encoding binary bit-packing
1个回答
0
投票
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 <--- how is this stored do you mean 8 bytes of 8 bits 
    Item7 Others
}
type Others struct{
    Other1 uint8  // number of bits = 4
    Other2 uint32 // number of bits = 21
    Other3 uint16 // number of bits = 9
}

一旦解决了这个问题,就可以很简单地对其进行编码,如下所示

func Encode(elem *Elements) []byte {
    // 60 bits
    b := make([]byte, size)
    b[0] = byte(elem.Item4 >> 52)
    b[1] = byte(elem.Item4 >> 44)
    b[2] = byte(elem.Item4 >> 36)
    b[3] = byte(elem.Item4 >> 28)
    b[4] = byte(elem.Item4 >> 20)
    b[5] = byte(elem.Item4 >> 12)
    b[6] = byte(elem.Item4 >> 4)
    b[7] = byte(elem.Item4 << 4)

    // 11 bits
    // 4 bits left
    b[7] |= byte(elem.Item5>>7) & 0b00001111
    b[8] = byte(elem.Item5 << 1) // 1 bit left

    // 5 bits
    b[8] |= byte(elem.Item1>>4) & 0b00000001
    b[9] = byte(elem.Item1 << 4) // 4 bits left

    // 3 bits
    b[9] |= (elem.Item3 << 1) & 0b00001110 // 1 bit left
    b[9] |= (elem.Item2 >> 1) & 0b00000001
    b[10] |= (elem.Item2 << 7) // store the remaining 1 bit here
.....
© www.soinside.com 2019 - 2024. All rights reserved.