IEEE 754用C语言转换为十进制 [英] IEEE 754 to decimal in C language
问题描述
我正在寻找将浮点数转换为C中十进制表示形式的最佳方法.我将尝试举一个例子:用户在IEEE754(1 1111111 10101 ...)中引入了一个数字必须返回十进制表示形式(例如25.6)
我已经尝试过使用掩码和按位运算,但是没有任何逻辑结果.
I'm looking the best way to transform a float number to its decimal representation in C. I'll try to give you an example: the user introduces a number in IEEE754 (1 1111111 10101...) and the program has to return the decimal representation (ex. 25.6)
I've tried with masks, and bitwise operations, but I haven't got any logical result.
推荐答案
我相信以下内容正在执行您描述的操作:
I believe the following is performing the operation you describe:
我使用int
作为中间表示,因为它的位数与浮点数(在我的机器上)相同,并且可以轻松地从二进制字符串进行转换.
I use the int
as an intermediate representation because it has the same number of bits as the float (on my machine), and it allowed easy conversion from the binary string.
#include <stdio.h>
union {
int i;
float f;
} myunion;
int binstr2int(char *s)
{
int rc;
for (rc = 0; '\0' != *s; s++) {
if ('1' == *s) {
rc = (rc * 2) + 1;
} else if ('0' == *s) {
rc *= 2;
}
}
return rc;
}
int main(void) {
// the input binary string (4 bytes)
char * input = "11000000110110011001100110011010";
float *output;
// convert to int, sizeof(int) == sizeof(float) == 4
int converted = binstr2int(input);
// strat 1: point memory of float at the int
output = (float*)&converted; // cast to suppress warning
printf("%f\n", *output); // -6.8
// strat 2: use a union to share memory
myunion.i = converted;
printf("%f\n", myunion.f); // -6.8
return 0;
}
正如@DanielKamilKozar所指出的,该int
的正确类型是uint32_t
.但是,这需要包含<stdint.h>
.
As @DanielKamilKozar points out, the correct type for that int
is uint32_t
. However, that would require including <stdint.h>
.
这篇关于IEEE 754用C语言转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!