Convert a byte array to float64

4k views Asked by At

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

There are 1 answers

0
Milo Christiansen On

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.