在 C 中将十六进制转换为 float

标签 c floating-point hex

我有一个十六进制数。字符串,我想将其转换为 float 。谁能提出任何想法?我在这个论坛上搜索,我得到了一篇提到以下解决方案的帖子。我知道第一个字符串被转换为十六进制数,然后十六进制数被转换为 float 。但我不明白这个 float_data = *((float*)&hexvalue); 是如何发生的。而且代码也不适用于此方法。

纠正1:我想我没有在这里说清楚。非常遗憾。此十六进制值 39 39 2e 30 35 转换为 ascii 时,它给出 99.05。我需要这个 ascii 作为 float 。 以下是我的代码:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
    char *my_data;
    double float_data;
    unsigned int hexvalue;
    my_data = malloc (100);
    my_data =strcpy(my_data, "39 39 2e 30 35");
    sscanf (my_data, "%x", &hexvalue);
    float_data = *((float*)&hexvalue);
    printf ("the floating n. is %f", float_data);
    free (my_data);
    return 0;
}

最佳答案

使用 "%hhx" 扫描转换为字符数组,附加空字符,然后转换为 float使用 atof()strtod() .

int main(void) {
  unsigned char uc[5+1];
  sscanf("39 39 2e 30 35", "%hhx%hhx%hhx%hhx%hhx", &uc[0], &uc[1], &uc[2], &uc[3], &uc[4]);
  uc[5] = 0;
  float f = atof(uc);
  printf("%f\n", f);
  return 0;
}

输出

99.050003

[编辑] 从 C99 开始可用,带有 scanf() :

hh Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to signed char or unsigned char. C11dr §7.21.6.2 11

关于在 C 中将十六进制转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869251/

相关文章:

java - setTextColor 的参数是一个 int 但可以接受 8 位十六进制值是怎么回事?

c - 没有关键字的大括号的作用不清楚

c++ - 当通过 C/C++ 中的 double 传输时,是否保证保留 float ?

c++ - std::ostream 的浮点格式

python - 读取日志数据的二进制文件并使用 int 输出到新文件(python)

php - mt_rand() 总是给我相同的数字

c - exec 函数只运行一些命令,不会运行 echo

c - 为什么我不能通过它的指针访问这个结构?

无法防止链表打印功能崩溃

javascript - 为什么我在 ECMAScript/ActionScript 3 中看到不精确的浮点结果?