How to Convert a Byte Slice to a Float64 in GoLang?

Barbara Streisand
Release: 2024-11-10 15:19:02
Original
139 people have browsed it

How to Convert a Byte Slice to a Float64 in GoLang?

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)
}
Copy after login

Output:

[24 45 68 84 251 33 9 64]
3.141592653589793
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template