reading float32 from a file

434 views
Skip to first unread message

Jerry

unread,
Nov 9, 2012, 4:59:36 AM11/9/12
to golan...@googlegroups.com
I got a file containing a 4 bytes float, which is previously generated by C program via fwrite(), and I know the byte-order is Big Endian.

now i want to read the float into memory as type float32, how can I do this?

My current solution is as follows:

package main
import (
"os"
"encoding/binary"
"math"
"fmt"
)

func main() {
fd, err := os.Open("file_containing_a_4bytes_float")
if err != nil {
return
}
b := make([]byte, 4)
fd.Read(b)
f := math.Float32frombits(binary.BigEndian.Uint32(b)) // I believe this is not idiomatic
fmt.Println(f)
}


I believe this is not the idiomatic way to read a float32 from a file, any hint on how to do this?

Regards,
Jiayu

minux

unread,
Nov 9, 2012, 6:21:03 AM11/9/12
to Jerry, golan...@googlegroups.com
defer fd.Close()
var f float32
err = binary.Read(fd, binary.BigEndian, &f)
        fmt.Println(err, f)
}

 

bryanturley

unread,
Nov 9, 2012, 10:34:10 AM11/9/12
to golan...@googlegroups.com
func main() {
        fd, err := os.Open("file_containing_a_4bytes_float")
        if err != nil {
                return
        }
defer fd.Close()
var f float32
err = binary.Read(fd, binary.BigEndian, &f)
        fmt.Println(err, f)
}

just make sure the float in the file is a proper float before you do that.
it is much more rare today but in the past trading floats between machines has been iffy.
 
Reply all
Reply to author
Forward
0 new messages