How to convert hex to float

前端 未结 3 1704
轻奢々
轻奢々 2020-12-21 00:47

I have to convert hex, represeneted as strings (e.g. \"0xC40C5253\") to float values (IEEE-754 conversion). I did not manage

3条回答
  •  时光取名叫无心
    2020-12-21 01:43

    The input is 32 bits, so must be treated as a 32-bit number. It is also unsigned, so should be parsed as a uint, not int. Finally, there is no need to use unsafe operations, and in fact as used here they will fail on a machine with a different byte order.

    Instead, use math.Float32frombits, which does exactly what you want:

    package main
    
    import (
        "fmt"
        "math"
        "strconv"
    )
    
    func main() {
        s := "C40C5253"
        n, err := strconv.ParseUint(s, 16, 32)
        if err != nil {
            panic(err)
        }
    
        nn := uint32(n)
    
        g := math.Float32frombits(nn)
        fmt.Println(g)
    }
    

    Output:

    -561.2863
    

    http://play.golang.org/p/y1ZjH9pscy

提交回复
热议问题