Using math.Float32fromBits()
We may use math.Float32fromBits()
to obtain a float32
value from its "binary" representation. But in order to use it, we need the 4 bytes data packed into a uint32
value. For that, we may use binary.ByteOrder.Uint32()
:
data := []byte{66, 106, 179, 86}
bits := binary.BigEndian.Uint32(data)
f := math.Float32frombits(bits)
fmt.Println(f)
Output (try it on the Go Playground):
58.675133
This solution is faster if we just want to read a single float32
value.
Using binary.Read()
Another option would be to use binary.Read()
to fill fixed-size values from an io.Reader
. If we have our data as a byte slice, we can use bytes.NewBuffer()
to obtain an io.Reader
from it:
data := []byte{66, 106, 179, 86}
var f float32
err := binary.Read(bytes.NewBuffer(data), binary.BigEndian, &f)
fmt.Println(f, err)
Output (try it on the Go Playground):
58.675133 <nil>
This solution is preferred if we have to read a series of float32
values from the input.