Converting Byte Slice to Float64 in GoLang
In GoLang, it might be necessary to convert a byte slice, represented as []uint8, into a float64. However, finding a straightforward solution online can be challenging. Attempting to convert the byte slice to a string and then to a float64 may result in data loss and incorrect values.
To address this issue, binary operations and mathematical functions provide an efficient method for converting byte slices to float64:
package main import ( "encoding/binary" "fmt" "math" ) // Convert []uint8 to float64 func Float64frombytes(bytes []byte) float64 { bits := binary.LittleEndian.Uint64(bytes) float := math.Float64frombits(bits) return float } // Convert float64 to []uint8 func Float64bytes(float float64) []byte { bits := math.Float64bits(float) bytes := make([]byte, 8) binary.LittleEndian.PutUint64(bytes, bits) return bytes } func main() { // Example: Converting math.Pi to byte slice and back to float64 bytes := Float64bytes(math.Pi) fmt.Println(bytes) float := Float64frombytes(bytes) fmt.Println(float) }
Output:
[24 45 68 84 251 33 9 64] 3.141592653589793
This code snippet demonstrates how to convert a byte slice to a float64 using the binary.LittleEndian package and the math.Float64frombits function. Conversely, it also shows how to convert a float64 back to a byte slice using the math.Float64bits and binary.LittleEndian.PutUint64 functions.
The above is the detailed content of How to Convert a Byte Slice to a Float64 in GoLang?. For more information, please follow other related articles on the PHP Chinese website!