Send float32 values ​​via udp socket

I am working on a Go project, and I would like to send float32 values ​​using UDPSocket. What I don't understand 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.

I am currently converting a byte of float32 → [] with the following function that I found on the Internet, but I'm not even sure that I get 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.

+3
source share
1 answer

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
+3
source

Source: https://habr.com/ru/post/1613086/


All Articles