dongmie3526 2018-05-16 07:44
浏览 3056
已采纳

如何将uint16序列转换为float32?

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.

  • 写回答

1条回答 默认 最新

  • dougaopu7938 2018-05-16 07:56
    关注

    Using 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.

    Using 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站