转换字节数组“[] uint8”在GoLang漂浮64 [英] Convert byte array "[]uint8" to float64 in GoLang
本文介绍了转换字节数组“[] uint8”在GoLang漂浮64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在GoLang中将 [] uint8
字节数组转换成 float64
。我无法在线找到此问题的解决方案。我已经看到了首先转换为字符串,然后转换为 float64
的建议,但这看起来并不奏效,它失去了它的价值,我最终得到了零。 / b>
示例:
metric.Value,_ = strconv.ParseFloat( string(column.Value),64)
它不起作用...
解决方案
例如,
package
$字节[]字节)float64 {
bits:= binary.LittleEndian.Uint64(bytes)
float:= math.Float64frombits(bits)
return float
}
func Float64bytes(float float64)[] byte [
bits:= math.Float64bits(float)
bytes:= make([] byte,8)
binary.LittleEndian。 PutUint64(字节,位)
返回字节
}
func main(){
字节:= Float64bytes(math.Pi)
fmt.Println(bytes)
float:= Float64frombytes(bytes)
fmt.Println(float)
}
输出:
[24 45 68 84 251 33 9 64]
3.141592653589793
I'm trying to convert a []uint8
byte array into a float64
in GoLang. I can't find a solution for this issue online. I've seen suggestions of converting to a string first and then to a float64
but this doesn't seem to work, it loses it's value and I end up with zeroes.
Example:
metric.Value, _ = strconv.ParseFloat(string(column.Value), 64)
And it doesn't work...
解决方案
For example,
package main
import (
"encoding/binary"
"fmt"
"math"
)
func Float64frombytes(bytes []byte) float64 {
bits := binary.LittleEndian.Uint64(bytes)
float := math.Float64frombits(bits)
return float
}
func Float64bytes(float float64) []byte {
bits := math.Float64bits(float)
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, bits)
return bytes
}
func main() {
bytes := Float64bytes(math.Pi)
fmt.Println(bytes)
float := Float64frombytes(bytes)
fmt.Println(float)
}
Output:
[24 45 68 84 251 33 9 64]
3.141592653589793
这篇关于转换字节数组“[] uint8”在GoLang漂浮64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文