﻿ 将十六进制转换为浮点数,反之亦然 - 代码日志

#### 将十六进制转换为浮点数,反之亦然

``````int is_hex(char arr[])
{
if (arr[0] == '0' && (arr[1] == 'x' || arr[1] == 'X')) {
return 1;
}
return 0;
}

int check_if_good(char arr[])
{
if (is_hex(arr)) {
int len = strlen(arr);
for (int i = 2; i < len; i++) {
if ((arr[i] > 'f' && arr[i] <= 'z') || (arr[i] > 'F' && arr[i] <= 'Z')) {
return 0;
}
}
}

return 1;
}

int main(int argc, const char * argv[])
{
float x;
char input[30];
scanf("%s", input);
printf("%s", input);
return 0;
}
``````

– 编辑：floris的额外代码.我试图在不使用任何额外库的情况下解决此问题,因此您无法使用stdint lib.

``````char input[30];
scanf("%s", input);
if(check_if_good(input)){  //Ignore this if-statement.
printf("Input is in hex form");
}
int num = convert_hex_string(input); // this function works perfectly. It return the int form of the hex.
double f = *((double*)&num);
printf("%f\n", f);
``````

``````#include <stdint.h>
#include <stdio.h>

int main(void) {
char myString[]="0x3f9d70a4";
uint32_t num;
float f;
sscanf(myString, "%x", &num);  // assuming you checked input
f = *((float*)&num);
printf("the hexadecimal 0x%08x becomes %.3f as a float\n", num, f);
}
``````

``````the hexadecimal 0x3f9d70a4 becomes 1.230 as a float
``````