gpt4 book ai didi

go - 以二进制编码无符号 16 位 float

转载 作者:IT王子 更新时间:2023-10-29 01:42:43 25 4
gpt4 key购买 nike

在 Go 中,我如何将 float 编码为字节数组,作为 16 位无符号 float 和 11 位显式尾数和 5 位显式指数?

似乎没有一个干净的方法来做到这一点。我唯一能想到的就是将它编码为 Convert byte array "[]uint8" to float64 in GoLang并手动截断位。

是否有“开始”的方式来做到这一点?

具体定义如下:

A 16 bit unsigned float with 11 explicit bits of mantissa and 5 bits of explicit exponent

The bit format is loosely modeled after IEEE 754. For example, 1 microsecond is represented as 0x1, which has an exponent of zero, presented in the 5 high order bits, and mantissa of 1, presented in the 11 low order bits. When the explicit exponent is greater than zero, an implicit high-order 12th bit of 1 is assumed in the mantissa. For example, a floatingvalue of 0x800 has an explicit exponent of 1, as well as an explicit mantissa of 0, but then has an effective mantissa of 4096 (12th bit is assumed to be 1). Additionally, the actual exponent is one-less than the explicit exponent, and the value represents 4096 microseconds. Any values larger than the representable range are clamped to 0xFFFF.

最佳答案

我不确定我是否正确理解编码(请参阅我对原始问题的评论),但这里有一个函数可以执行您想要的操作:

func EncodeFloat(seconds float64) uint16 {
us := math.Floor(1e6*seconds + 0.5)
if us < 0 {
panic("cannot encode negative value")
} else if us > (1<<30)*4095+0.5 {
return 0xffff
}
usInt := uint64(us)
expBits := uint16(0)
if usInt >= 2048 {
exp := uint16(1)
for usInt >= 4096 {
exp++
usInt >>= 1
}
usInt -= 2048
expBits = exp << 11
}
return expBits | uint16(usInt)
}

(代码在http://play.golang.org/p/G599VOBMcL)

关于go - 以二进制编码无符号 16 位 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29789610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com