0

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
}
user38138
  • 11
  • 3
  • Will each item hold only one value i.e. only one of `Elements` struct field is set? Or are all 5 fields potentially set & need to be marshaled/unmarshaled? – colm.anseo Aug 12 '20 at 23:48
  • 1
    Use [bit shifts and bitwise ORs](https://golang.org/ref/spec#Arithmetic_operators) to assemble the bytes you want. Since you have 82 bits total and the smallest unit of data is a byte you will need six padding bits somewhere. – Peter Aug 13 '20 at 02:59
  • @colm.anseo Each item holds one value. – user38138 Aug 13 '20 at 07:52
  • You might want to think about another solution to your problem, maybe encode all your objects with `encoding/binary` and then compress it. Working with bits makes things more complex. Only you know the cost for your use-case but maybe this is an alternative for you. – gonutz Aug 13 '20 at 18:38

0 Answers0