1

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)
}
ansrivas
  • 597
  • 2
  • 9
  • 14
  • 2
    Is this honestly a bottleneck in your application? Do some experimenting with reading and writing binary data, and it should become clear to you what approach you need to take. –  Sep 03 '17 at 01:01
  • No, this is not a bottleneck really. I have already profiled my code and found that his conversion is among the slow parts, so this was an attempt to find if this can actually be even done at all. – ansrivas Sep 03 '17 at 08:26

1 Answers1

1

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.

Milo Christiansen
  • 3,204
  • 2
  • 23
  • 36