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

时间:2015-09-30 14:52:01

标签: c floating-point hex

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

更正1:我想我在这里没有提及。非常遗憾。转换为ascii时,此十六进制值39 39 2e 30 35,然后它给出99.05。我需要这个ascii as float no。 以下是我的代码:

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

3 个答案:

答案 0 :(得分:2)

使用"%hhx"扫描到字符数组中,附加空字符,然后使用floatatof()转换为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

[edit]自C99以来可用scanf()

  

hh指定以下diouxX或{ {1}}转换说明符适用于具有指向nsigned char的类型指针的参数。 C11dr§7.21.6.211

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

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

错误检查尚未完成,因此请根据需要添加。