例如:16777219.0 十进制转换为位
16777219 -> 1 0000 0000 0000 0000 0000 0011 mantissa: 23 bit 0000 0000 0000 0000 0000 001 exponent: 24+127 = 151 151 -> 10010111 result shoud be: 0_10010111_000 0000 0000 0000 0000 0001 1001011100000000000000000000001
但是:
fmt.printf("%b\n", math.float32bits(float32(16777219.0))) // 1001011100000000000000000000010
为什么 go float32bit() 结果不是预期的?
参考:
更新:
fmt.Printf("16777216.0:%b\n", math.Float32bits(float32(16777216.0))) fmt.Printf("16777217.0:%b\n", math.Float32bits(float32(16777217.0))) //16777216.0:1001011100000000000000000000000 //16777217.0:1001011100000000000000000000000 fmt.Printf("16777218.0:%b\n", math.Float32bits(float32(16777218.0))) //16777218.0:1001011100000000000000000000001 fmt.Printf("16777219.0:%b\n", math.Float32bits(float32(16777219.0))) fmt.Printf("16777220.0:%b\n", math.Float32bits(float32(16777220.0))) fmt.Printf("16777221.0:%b\n", math.Float32bits(float32(16777221.0))) //16777219.0:1001011100000000000000000000010 //16777220.0:1001011100000000000000000000010 //16777221.0:1001011100000000000000000000010 fmt.Printf("000:%f\n", math.Float32frombits(0b_10010111_00000000000000000000000)) // 000:16777216.000000 fmt.Printf("001:%f\n", math.Float32frombits(0b_10010111_00000000000000000000001)) // 001:16777218.000000 fmt.Printf("010:%f\n", math.Float32frombits(0b_10010111_00000000000000000000010)) // 010:16777220.000000 fmt.Printf("011:%f\n", math.Float32frombits(0b_10010111_00000000000000000000011)) // 011:16777222.000000
规则是什么?
go 给出正确的 ieee-754 二进制浮点结果 - 舍入到最接近的值,平局为偶数。
float32 the set of all ieee-754 32-bit floating-point numbers
十进制
16777219
是二进制的
1000000000000000000000011
对于 32 位 ieee-754 浮点二进制,24 位整数尾数为
100000000000000000000001.1
四舍五入到最接近的值,偶数给出
100000000000000000000010
删除 23 位尾数的隐式一位得到
00000000000000000000010
package main import ( "fmt" "math" ) func main() { const n = 16777219 fmt.printf("%d\n", n) fmt.printf("%b\n", n) f := float32(n) fmt.printf("%g\n", f) fmt.printf("%b\n", math.float32bits(f)) }
https://www.php.cn/link/f0bbf5fb2b067fda7b491dc2307411e4
16777219 1000000000000000000000011 1.677722e+07 1001011100000000000000000000010
以上是Go Float32bit() 结果不是预期的的详细内容。更多信息请关注PHP中文网其他相关文章!