golang 将4字节的16进制转化为十进制的浮点数

package main

import (
    "fmt"
    "math"
    "strconv"
)

func main() {
    //i := "00009841"
    //i :="41980000"
    i :="420E0000"
    n, _:= strconv.ParseUint(i, 16, 32)
    f := math.Float32frombits(uint32(n))
    fmt.Println(fmt.Sprintf("%f", f))
    fmt.Printf("%s\n", "hello world")
}

 

 

package main

import (
    "bytes"
    "encoding/binary"
    "encoding/hex"
    "log"
    "math"
    "strconv"
)

func main(){
    src := strconv.FormatInt(16, 16)
    test, er := hex.DecodeString(src)
    log.Println(test, er)

    bytesBuffer := bytes.NewBuffer([]byte{})
    err := binary.Write(bytesBuffer, binary.BigEndian, int32(100))
    b:= bytesBuffer.Bytes()
    log.Println(b,err)
    log.Println(IntToBytes(15))


    //s := "C4 0C 52 53"
    s := "53520CC4"
    log.Println(parse_read(s))
    log.Println(parse_math(s))

}

func IntToBytes(n int) []byte {
    data := int64(n)
    bytebuf := bytes.NewBuffer([]byte{})
    binary.Write(bytebuf, binary.BigEndian, data)
    return bytebuf.Bytes()
}

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
}

//注意事项在截取报文信息的时候要区分 大小 端字节序

你可能感兴趣的:(go)