如何仅使用 4 位来表示 Go 中的数字?

How can I represent a number in Go using only 4 bits?

我正在尝试将数字的表示压缩为更少的位。例如,现在我正在使用 float64 来表示 8.0 这样的数字。我只需要 4 位来表示 8.0,所以我试图找到一种方法将 float64 表示转换为 4 位表示。我知道我可以使用 uint8 仅使用 8 位来表示 8,但这对我的应用程序来说还不够。我需要在 space 中压缩那些额外的位。

我查看了 Go 标准库,但没有找到任何可以让我用少于 8 位表示数字的东西。我错过了可以帮助我做到这一点的包裹吗?我该如何解决这个问题?

Go 标准库确实有一个可变长度数字的示例。

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)
}

游乐场:https://play.golang.org/p/-p6M6OSHcMF

输出:

8 1 [16]
8 1