How to convert hex to float

前端 未结 3 1708
轻奢々
轻奢々 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:45

    Here are two different approaches that produce -561.2863: http://play.golang.org/p/Y60XB820Ib

    import (
        "bytes"
        "encoding/binary"
        "encoding/hex"
        "math"
        "strconv"
    )
    
    func parse_read(s string) (f float32, err error) {
        b, err := hex.DecodeString(s)
    
        if err != nil {
            return
        }
    
        buf := bytes.NewReader(b)
    
        err = binary.Read(buf, binary.BigEndian, &f)
    
        return
    }
    
    func parse_math(s string) (f float32, err error) {
        i, err := strconv.ParseUint(s, 16, 32)
    
        if err != nil {
            return
        }
    
        f = math.Float32frombits(uint32(i))
    
        return
    }
    

提交回复
热议问题