简体   繁体   English

将float64转换为字节数组

[英]Convert float64 to byte array

How can I convert a float64 variable to big endian encoded byte array? 如何将float64变量转换为big endian编码的字节数组?

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? 为了清楚起见,我应该如何在以下操场中实现float64ToByte函数?

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

Use math.Float64bits to get the float64 as a uint64 . 使用math.Float64bitsfloat64作为uint64 Use shifting and conversions on the uint64 to convert to a desired sequence of bytes. 使用uint64上的移位和转换转换为所需的字节序列。 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. 您可以使用encoding / binaryuint64转换为字节,而不是直接写出移位和转换。 Here's how to encode the float64 in big endian order using that package: 以下是使用该包以大端顺序编码float64方法:

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: 这是问题中float64ToByte函数的big endian实现:

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

playground example 操场的例子

You can use binary.Write() from package "encoding/binary" : 您可以使用包"encoding/binary" binary.Write()

func float64ToByte(f float64) []byte {
    var buf bytes.Buffer
    err := binary.Write(&buf, binary.BigEndian, f)
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    return buf.Bytes()
}

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

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

On my system it had to be little endianed: 在我的系统上,它必须是小结束:

func float64ToByte(f float64) []byte {
    var buf bytes.Buffer
    err := binary.Write(&buf, binary.LittleEndian, f)
    if err != nil {
        fmt.Println("binary.Write failed:", err)
    }
    return buf.Bytes()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM