转换字节片"[] uint8";在GoLang中浮动 [英] Convert byte slice "[]uint8" to float64 in GoLang

查看:205
本文介绍了转换字节片"[] uint8";在GoLang中浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在GoLang中将[]uint8字节片转换为float64.我找不到在线解决此问题的方法.我已经看到了先转换为字符串然后转换为float64的建议,但这似乎不起作用,它失去了它的值,最终以零结束.

I'm trying to convert a []uint8 byte slice 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.

示例:

metric.Value, _ = strconv.ParseFloat(string(column.Value), 64)

那是行不通的...

推荐答案

例如,

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)
}

输出:

[24 45 68 84 251 33 9 64]
3.141592653589793

这篇关于转换字节片"[] uint8";在GoLang中浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆