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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!