我有一个十六进制数。字符串,我想将其转换为 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 followingd
,i
,o
,u
,x
,X
, orn
conversion specifier applies to an argument with type pointer tosigned char
orunsigned char
. C11dr §7.21.6.2 11
关于在 C 中将十六进制转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869251/