简体   繁体   English

Golang 无法使用 math.Float64frombits 将 []byte("1575455669.4") 转换为 float64

[英]Golang cannot convert []byte("1575455669.4") to float64 using math.Float64frombits

I have the following code:我有以下代码:

x := []byte("1575455669.4")
bits := binary.LittleEndian.Uint64(x)
f := math.Float64frombits(bits)

On calling fmt.Println(f) I expect 1.5754556694e+09 .在调用fmt.Println(f)我期望1.5754556694e+09 But instead I end up with 1.451098468672448e-47但是我最终得到了1.451098468672448e-47

When I try the same conversion through strconv.ParseFloat(string(x), 64) I get the correct result.当我通过strconv.ParseFloat(string(x), 64)尝试相同的转换时strconv.ParseFloat(string(x), 64)我得到了正确的结果。 What am I doing wrong here?我在这里做错了什么?

This:这个:

x := []byte("1575455669.4")

will give you the (UTF-8 encoded) bytes of the "1575455669.4" string.将为您提供"1575455669.4"字符串的(UTF-8 编码)字节。 This has nothing to do with the memory representation of the floating point number 1575455669.4 which uses the IEEE 754 standard.这与使用IEEE 754标准的浮点数1575455669.4的内存表示无关。 But what you do next would assume just that:但是你接下来要做的只是假设:

bits := binary.LittleEndian.Uint64(x)
f := math.Float64frombits(bits)

You have a number given as its base-10 string representation, you have to use strconv.ParseFloat(string(x), 64) to parse it and have it as a float64 .您有一个数字作为其 base-10 字符串表示形式,您必须使用strconv.ParseFloat(string(x), 64)来解析它并将其作为float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM