16

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

1
  • 1
    @Flimzy:I edited the question(big endian). Commented Apr 29, 2017 at 13:55

4 Answers 4

26

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

Sign up to request clarification or add additional context in comments.

2 Comments

this anwser tells you how to do it, but If you are intrested in why turn a float point number to a uint32, refer to IEEE754 standard for detail.
@user4985526 What?
13

You can use binary.Write() from package "encoding/binary" :

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

3 Comments

Note: The code is correct, but most computers uses little endian: binary.LittleEndian.
@HelinWang True but if you are inserting into sorted key-value store, like Bolt or Badger, you want big endian.
For parsing font files, BigEndian is also required. Regardless, the main essence of the answer has been conveyed. As for which endianness to use, it can be modified according to the requirements.
1

Adding yet another flavor to this question.

func float64ToBytes(f64 float64) []byte {
    bts := make([]byte, 8)
    (*(*[]float64)(unsafe.Pointer(&bts)))[0] = f64
    return bts
}

func bytesToF64(bts []byte) float64 {
    return *(*float64)(unsafe.Pointer(&bts[0]))
}

You could even make it with zero allocation like this

func float64ToBytes(f64 float64) []byte {
    var bts []byte
    sh := (*reflect.SliceHeader)(unsafe.Pointer(&bts))
    sh.Data = uintptr(unsafe.Pointer(&f64))
    sh.Len = 8
    sh.Cap = sh.Len
    return bts
}

Comments

0

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()
}

2 Comments

Your answer is similar to har07, and I don't think a new answer is warranted just because of a difference in endianness. Your response only serves to remind users to be aware of their computer's endianness, but if that's the case, it might be better to just edit har07's answer directly.
Additionally, your mention of "my system" is not very clear because it represents a subjective viewpoint. Different users may have systems that are not the same as yours, so if it's necessary to mention, I believe teaching users how to determine their system's endian would be more beneficial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.