在 C 中将十六进制转换为浮点数

Convert hex to float in C

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

更正1:我好像没说清楚。非常遗憾。这个十六进制值 39 39 2e 30 35 当转换为 ascii 时,它给出 99.05。我需要这个 ascii 作为浮点数。 以下是我的代码:

#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;
}

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;
}

使用 "%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

[编辑] 自 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

此代码将进行新的转换,支持任意长度的输入。

#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 = '[=10=]';
    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;
}

未进行错误检查,如有需要请添加。