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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题