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

如何将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.

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

报告相同问题?

悬赏问题

  • ¥15 已知平面坐标系(非直角坐标系)内三个点的坐标,反求两坐标轴的夹角
  • ¥15 webots有问题,无响应
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上