I've a sequence [66 106 179 86]
(those numbers are two 16bit register in modbus) generated by modbus library(conversion code), now how can I convert this sequence in a 32 float number?
I've tried []uint32{66,106, 179, 86}
as argument for Float32frombits
but doesn't accept uint32 lists.
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.
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.