I'm working on a Go project and I would like to send float32 values using an UDPSocket. The thing that I don't understand is what is the best way to convert these numbers to a byte buffer before sending them and how to convert them back to float32 after receiving them.
At the moment I'm converting float32->[]byte with the following function that I've found online, but I'm not even sure I'm getting what I want:
func Float32bytes(float float32) []byte {
bits := math.Float32bits(float)
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, bits)
return bytes
}
I still don't know how to convert them to float32.
For example,
package main
import (
"encoding/binary"
"fmt"
"math"
)
func Float32Bytes(float float32) []byte {
bits := math.Float32bits(float)
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, bits)
return bytes
}
func BytesFloat32(bytes []byte) float32 {
bits := binary.LittleEndian.Uint32(bytes)
float := math.Float32frombits(bits)
return float
}
func main() {
pi := float32(math.Pi)
b := Float32Bytes(pi)
f := BytesFloat32(b)
fmt.Println(f, f == pi, BytesFloat32(Float32Bytes(pi)) == pi)
}
Output:
3.1415927 true true