所以,我有一些代码的问题。
我希望这个函数接受一个字节数组(目前用单字节测试),将字节转换成二进制,然后将其附加到“1”中,以便在计算中使用。
前任:
输出:011100000--->1.011100000
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
double calcByteValue(uint8_t data[], int size);
int main() {
uint8_t test[10];
test[0] = 0x0e;
double d = calcByteValue(test, 8);
return 0;
}
double calcByteValue(uint8_t data[], int size) {
int i;
uint8_t bits[21];
char binary[100];
char str[100] = "1.";
for (i = 0;i < size;i++) {
bits[i] = (data[0] >> i) & 1;
if (bits[i] == 0) {
binary[i] = '0';
printf("0(%d)\n", i);
} else {
binary[i] = '1';
printf("1(%d)\n", i);
}
}
strcat(str, binary);
float d = atof(str);
printf("%f\n", d);
return 0;
//return pow(-1, bits[0]) * pow(2, (128-127)) * atof(str));
}
这是我的输出,出于某种原因,它在整个循环中运行得很好,但只打印了6个原始位,去掉了最后几个位。我做错什么了???
0(0)
1(1)
1(2)
1(3)
0(4)
0(5)
0(6)
0(7)
1.011100
最佳答案
第一:
strcat(str, binary);
您从未以null结尾过
binary
数组。你必须把它当作一根绳子。 char binary[100];
binary
在块作用域中定义,未显式初始化的块作用域自动对象具有不确定值。以下是如何空终止数组:
binary[size] = '\0';
第二:
按相反的顺序插入位值。将
(data[0] >> 7) & 1
用于binary[0]
,将(data[0] >> 6) & 1
用于binary[1]
等等。同时,
printf
与%f
转换规范在小数点后打印6位数字。如果需要更多的数字(例如16),可以指定如下精度:printf("%.16f\n", d);
您还为object
float
使用了类型d
,如果您发现float
没有足够的精度,可以使用类型double
。