title: How to encode struct into binary with bit packing in Golang
body: <p>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 <a href="https://golang.org/pkg/encoding/binary/" rel="nofollow noreferrer">Encoding/binary</a> packs each item minimum as one byte. Therefore I need another solution. How can I encode struct elements as specified bit number in Go?</p>
  <p>For example; Item1 = 00001101 Item2 = 00000110  Result will be as 01101110</p>
  <pre><code>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
  }
  </code></pre>