dongzj2015 2017-04-29 08:13
浏览 257
已采纳

将float64转换为字节数组

How can I convert a float64 variable to big endian encoded byte array?

var f float64 = 12.666512
var result []byte = float64ToByte(f);
fmt.Printf("result:%f",result)

For the sake of clarity how should I implement float64ToByte function in the following playground?

https://play.golang.org/p/LevxCDd7mK

  • 写回答

3条回答 默认 最新

  • duanjing9739 2017-04-29 13:21
    关注

    Use math.Float64bits to get the float64 as a uint64. Use shifting and conversions on the uint64 to convert to a desired sequence of bytes. For example, here's how to encode a float in big endian order:

    var buf [8]byte
    n := math.Float64bits(f)
    buf[0] = byte(n >> 56)
    buf[1] = byte(n >> 48)
    buf[2] = byte(n >> 40)
    buf[3] = byte(n >> 32)
    buf[4] = byte(n >> 24)
    buf[5] = byte(n >> 16)
    buf[6] = byte(n >> 8)
    buf[7] = byte(n)
    

    You can use the encoding/binary to convert the uint64 to bytes instead of writing out the shifts and conversions directly. Here's how to encode the float64 in big endian order using that package:

    var buf [8]byte
    binary.BigEndian.PutUint64(buf[:], math.Float64bits(f))
    

    The little endian code is:

    var buf [8]byte
    binary.LittleEndian.PutUint64(buf[:], math.Float64bits(f))
    

    Here's the big endian implementation of the float64ToByte function in the question:

    func float64ToByte(f float64) []byte {
       var buf [8]byte
       binary.BigEndian.PutUint64(buf[:], math.Float64bits(f))
       return buf[:]
    }
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?