如何将十六进制转换为浮点数 [英] How to convert hex to float

查看:1956
本文介绍了如何将十六进制转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将表示为string s(例如"0xC40C5253")的hex转换为浮点值( IEEE-754 转换).我没有使用strconv.ParseFloat函数做到这一点.还有什么我要用的吗? 到目前为止我找不到.我还尝试过先将其转换为整数,然后转换为浮点数,但结果是错误的.

I have to convert hex, represeneted as strings (e.g. "0xC40C5253") to float values (IEEE-754 conversion). I did not manage to do that using the strconv.ParseFloat function. Is there anything else I have to use? I couldn't find it so far. I also tried converting it to an integer first and then to a float, but the results were wrong.

我最后一次尝试的代码:

Code of my last try:

package main

import (
  "fmt"
  "strconv"
)

func main () {
  x, err := strconv.ParseInt("C40C5253", 16, 64) 
  f, err := strconv.ParseFloat(fmt.Sprintf("%d", x), 64) 

  if err != nil {
    fmt.Printf("Error in conversion: %s\n", err)
  } else {
    fmt.Println(f)
  }
}

推荐答案

首先需要说明输入的位长.由于十六进制表示形式有4个字节(8个十六进制数字),因此很可能是float32(需要询问者澄清).

First it needs to be stated the bit-length of the input. Since the hex representation has 4 bytes (8 hex digits), it is most likely a float32 (needs clarification from the asker).

您可以使用 strconv.ParseUint() uint32 >. ParseUint()总是返回uint64,它在内存中使用8个字节,因此您必须将其转换为使用4个字节的uint32,就像float32:

You can parse the bytes from the hex representation into an uint32 using strconv.ParseUint(). ParseUint() always returns uint64 which uses 8 bytes in memory so you have to convert it to uint32 which uses 4 bytes just like float32:

s := "C40C5253"
n, err := strconv.ParseUint(s, 16, 32)
if err != nil {
    panic(err)
}
n2 = uint32(n)

现在您有了字节,但是它们存储在类型为uint32的变量中,因此将其解释为整数的字节.而且您想将它们解释为IEEE-754浮点数的字节,可以使用 unsafe 包来做到这一点:

Now you have the bytes but they are stored in a variable of type uint32 and therefore interpreted as the bytes of an integer. And you want to interpret them as the bytes of a IEEE-754 floating point number, you can use the unsafe package to do that:

f := *(*float32)(unsafe.Pointer(&n2))
fmt.Println(f)

输出(在进入游乐场上尝试)

-561.2863

注意:

JimB指出,对于第二部分(将uint32转换为float32), math 软件包具有内置函数 math.Float32frombits() :

As JimB noted, for the 2nd part (translating uint32 to float32) the math package has a built-in function math.Float32frombits() which does exactly this under the hood:

f := math.Float32frombits(n2)

这篇关于如何将十六进制转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆