[英]Convert hex to float in C
我有一個十六進制的數字。 字符串,我想將其轉換為float。 有人可以提出任何想法嗎? 我在此論壇上進行了搜索,並收到了一篇提到以下解決方案的帖子。 我知道先將字符串轉換為十六進制數字,然后將十六進制數字轉換為浮點型。 但是我不明白這個float_data = *((float*)&hexvalue);
正在發生。 而且代碼也不適用於此方法。
更正1:我想我在這里沒有明確提及。 非常遺憾。 轉換為ascii時,此十六進制值39 39 2e 30 35
,則得出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"
掃描到字符數組,附加空字符,然后使用atof()
或strtod()
轉換為float
。
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
[edit]自C99起可用,帶有scanf()
:
hh
指定后面的d
,i
,o
,u
,x
,X
或n
轉換說明符適用於類型為帶signed char
或unsigned char
指針的參數。 C11dr§7.21.6.211
float_data = *((float*)&hexvalue);
將&hexvalue
視為float
的指針,然后從&hexvalue
指向float
位置讀取數據。
根據環境的不同,此代碼可能會起作用。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
char *my_data;
double float_data;
unsigned int hexvalue[4];
unsigned char floatdata_hex[4];
int i;
my_data = malloc (100);
strcpy(my_data, "39 39 2e 30 35"); /* the assignment isn't needed */
/* the original code will read only one hex value, not four or five */
sscanf (my_data, "%x%x%x%x", &hexvalue[0], &hexvalue[1], &hexvalue[2], &hexvalue[3]); /* read to int */
for (i = 0; i < 4; i++) floatdata_hex[i] = hexvalue[i]; /* and convert them to char later */
float_data = *((float*)floatdata_hex);
/* the value may be too small to display by %f */
printf ("the floating n. is %.15g", float_data);
free (my_data);
return 0;
}
該代碼將進行新的轉換,支持任意長度的輸入。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double ascii_string_to_float(const char *str)
{
double ret = 0.0;
char *work1;
char *work2;
char *tok, *out;
size_t len = strlen(str);
work1 = malloc(len + 1);
work2 = malloc(len + 1);
if (work1 == NULL || work2 == NULL)
{
if (work1 != NULL) free(work1);
if (work2 != NULL) free(work2);
exit(1);
}
strcpy(work1, str);
out = work2;
tok = strtok(work1, " ");
do {
int tmp;
sscanf(tok, "%x", &tmp);
*(out++) = tmp;
} while ((tok = strtok(NULL, " ")) != NULL);
*out = '\0';
sscanf(work2, "%lf", &ret);
free(work1);
free(work2);
return ret;
}
int main(void)
{
const char *my_data = "39 39 2e 30 35";
double float_data;
float_data = ascii_string_to_float(my_data);
printf("the floating n. is %f", float_data);
return 0;
}
錯誤檢查尚未完成,因此請根據需要添加它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.