簡體   English   中英

在 GoLang 中將字節切片“[]uint8”轉換為 float64

[英]Convert byte slice “[]uint8” to float64 in GoLang

我正在嘗試將[]uint8字節切片轉換為 GoLang 中的float64 我在網上找不到這個問題的解決方案。 我已經看到了先轉換為字符串然后轉換為float64但這似乎不起作用,它失去了它的價值,最終我得到了零。

例子:

metric.Value, _ = strconv.ParseFloat(string(column.Value), 64)

它不起作用......

例如,

package main

import (
    "encoding/binary"
    "fmt"
    "math"
)

func Float64frombytes(bytes []byte) float64 {
    bits := binary.LittleEndian.Uint64(bytes)
    float := math.Float64frombits(bits)
    return float
}

func Float64bytes(float float64) []byte {
    bits := math.Float64bits(float)
    bytes := make([]byte, 8)
    binary.LittleEndian.PutUint64(bytes, bits)
    return bytes
}

func main() {
    bytes := Float64bytes(math.Pi)
    fmt.Println(bytes)
    float := Float64frombytes(bytes)
    fmt.Println(float)
}

輸出:

[24 45 68 84 251 33 9 64]
3.141592653589793

我認為 Go 文檔中的這個例子就是你要找的: http : //golang.org/pkg/encoding/binary/#example_Read

var pi float64
b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}
buf := bytes.NewReader(b)
err := binary.Read(buf, binary.LittleEndian, &pi)
if err != nil {
  fmt.Println("binary.Read failed:", err)
}
fmt.Print(pi)

打印 3.141592653589793

正如評論所讀,這完全取決於您在[]uint8切片中擁有的數據類型。

如果它是以 Little Endian 順序表示 IEEE 754 浮點值的字節,則使用 Kluyg 或 peterSo(不使用反射的更好性能)答案。

如果它是用 Latin-1/UTF-8 編碼的文本表示,那么你應該能夠做你剛剛做的事情:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var f float64
    text := []uint8("1.23") // A decimal value represented as Latin-1 text

    f, err := strconv.ParseFloat(string(text), 64)
    if err != nil {
        panic(err)
    }

    fmt.Println(f)
}

結果:

1.23

游樂場: http : //play.golang.org/p/-7iKRDG_ZM

我希望這個黑客有幫助。 它的目的是將二進制數的長流轉換為浮點數。

例如:0110111100010010100000111100000011001010001000010000100111000000 -> -3.1415

func binFloat(bin string) float64 {

    var s1 []byte
    var result float64

    if len(bin) % 8 == 0 {

            for i := 0; i < len(bin) / 8; i++ {

                    //Chop the strings into a segment with a length of 8.
                    //Convert the string to Integer and to byte

                    num, _ := strconv.ParseInt(bin[8*i: 8*(i + 1)], 2, 64) 
                    //Store the byte into a slice s1
                    s1 = append(s1, byte(num)) 
            }

    }

    //convert the byte slice to a float64. 
    //The algorithm below are copied from golang binary examples. 

    buf := bytes.NewReader(s1)

    //You can also change binary.LittleEndian to binary.BigEndian
    //For the details of Endianness, please google Endianness

    err := binary.Read(buf, binary.LittleEndian, &result) 

    if err != nil {

            panic(err)
            fmt.Println("Length of the binary is not in the length of 8")
    }

    return result
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM