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