So, I am having trouble with some code.
I want this function to take in a byte array(testing with single byte for now), convert the byte into binary and then append it to a “1.” to use in a calculation.
ex:
ouput: 01110000 —-> 1.01110000
#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));
}
Here is my output, for some reason it is going through the whole loop just fine, but only printing 6 of the original bits, knocking off the last couple ones. What am I doing wrong???
0(0)
1(1)
1(2)
1(3)
0(4)
0(5)
0(6)
0(7)
1.011100
First:
You never null terminated the
binaryarray. You have to to use it as a string.binaryis defined at block scope, and block scope automatic objects that are not explicitly initialized have an indeterminate value.Here is how to null terminate the array:
Second:
you are inserting the bits values in the reverse order. Put
(data[0] >> 7) & 1forbinary[0],(data[0] >> 6) & 1forbinary[1]and so on.Also
printfwith%fconversion specification prints 6 digits after the decimal point. If you want more digits (e.g., 16), you can specify the precision like this:printf("%.16f\n", d);You are also using the type
floatfor objectd, if you find you don’t have enough precision withfloat, you can use typedouble.