英文:
Convert a byte array to float64
问题
我正在尝试将从文件中读取的字节数组转换为浮点数。我可以使用strconv.ParseFloat
,但我想知道是否有任何更快的方法来实现这一点,而不是进行字符串转换的开销。
以下代码片段来自另一个帖子:这里,但显然它对上述描述的情况不起作用。
提前感谢您的建议。
package main
import (
"encoding/binary"
"fmt"
"math"
)
func Float64frombytes(bytes []byte) float64 {
bits := binary.LittleEndian.Uint64(bytes)
float := math.Float64frombits(bits)
return float
}
func main() {
// 这是从文件中读取的,因此作为字节数组可用
input := []byte("1.11")
// 这显然会引发异常。
float := Float64frombytes(input)
fmt.Println(float)
}
英文:
I am trying to convert a byte-array read from a file, which actually happens to be a float. I can go ahead and use strconv.ParseFloat
but I am wondering if there is any faster way to achieve this, rather than this string conversion overhead?
The following snippet is from another post : here but obviously it doesn't work for the scenario described above.
Thanks in advance for your suggestions.
package main
import (
"encoding/binary"
"fmt"
"math"
)
func Float64frombytes(bytes []byte) float64 {
bits := binary.LittleEndian.Uint64(bytes)
float := math.Float64frombits(bits)
return float
}
func main() {
// This is read from a file, so its avaible as a byte array
input := []byte("1.11")
// This throws an exception obviously.
float := Float64frombytes()
fmt.Println(float)
}
答案1
得分: 1
不,没有其他方法可以做到这一点。
你列出的不起作用的替代方法将是最好的方法,如果浮点数直接以二进制形式存储,但由于它以字符串形式存储,strconv.ParseFloat
是唯一的方法。
抱歉。
英文:
No, there is no other way to do this.
The aproach you list as a non-working alternative would be th best method if the float was stored in directly in binary, but since it is stored as a string strconv.ParseFloat
is the only way.
Sorry.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论