How to encode struct into binary with bit packing in Golang

419 Views Asked by At

I am trying to encode large data structs into binary. I have specified number of bits for each struct element. So I need to encode struct into binary according to bit length. Standard Golang library Encoding/binary packs each item minimum as one byte. Therefore I need another solution. How can I encode struct elements as specified bit number in Go?

For example; Item1 = 00001101 Item2 = 00000110 Result will be as 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
}
0

There are 0 best solutions below