I am trying to compress the representation of a number into fewer bits. For example, right now I am using a float64
to represent a number such as 8.0
. I only need 4 bits to represent 8.0
, so I was trying to find a way to convert the float64
representation into a 4 bit representation. I know I can use an uint8
to represent 8 using only 8 bits, but that is not enough for my application. I need to squeeze those little extra bits in space.
I looked around the Go standard library, but did not find anything that would allow me to represent a number in less than 8 bits. Did I miss a package that can help me do this? How can I approach this problem?
The Go standard library does have an example of variable-length numbers.
package main
import (
"encoding/binary"
"fmt"
)
func main() {
buf := make([]byte, binary.MaxVarintLen64)
x := int64(8)
n := binary.PutVarint(buf[:cap(buf)], x)
buf = buf[:n]
fmt.Println(x, len(buf), buf)
y, m := binary.Varint(buf)
fmt.Println(y, m)
}
Playground: https://play.golang.org/p/-p6M6OSHcMF
Output:
8 1 [16]
8 1