dty97501 2015-10-25 11:01
浏览 173
已采纳

通过udp套接字发送float32值

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.

  • 写回答

1条回答 默认 最新

  • doumen5087 2015-10-25 11:58
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器