Convert byte slice "[]uint8" to float64 in GoLang

user3435186 picture user3435186 · Mar 18, 2014 · Viewed 26.3k times · Source

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.

Example:

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

And it doesn't work...

Answer

peterSO picture peterSO · Mar 18, 2014

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