Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 1 month ago.
how to convert binary data to float value?
Hello all, For my data logger project I'm logging data to a SD card. Here I'm storing the data in binary format. I'm logging accelerometer and temp&humidity sensors. I could read data byte by byte. Hence to print ADXL data (two bytes), I combine each two byte data. Hence four bytes has to be combined to get temparature data. Unfortunately for temparature I failed to print actual data. There is some conversion problem. I'm looking some help regarding how to convert data to floats.
Code to read and print binary to uint16_t ( accelerometer data): working
while ((nr = fgetc(logFile)) != EOF){
pc.printf(" \r\n %d ",nr);
acc_con[i] = nr;
if (i == 1){
acc = (acc_con[1]<<8) | acc_con[0];
pc.printf(" \r\n %i ",acc);
i = 0;}
else i++;
}
Code to read and print binary to float ( temparature data): Not working
while ((nr = fgetc(logFile)) != EOF){
pc.printf(" \r\n %d ",nr);
humicon[i] = nr;
if (i == 3){
hum = (humicon[0] << 24) | (humicon[1] << 16) | (humicon[2] << 8) | humicon[3];
pc.printf(" \r\n %f ",hum);
i = 0;}
else i++;
}
The byte by byte raw data from variable nr is: 24, 58, 46, 66, and the output from variable hum is: 406466112.000000
How did you write humicon in the first place? And what is the format you read it from your device like?
posted by Erik - 13 Dec 2016I don't know much about formats. I get the correct output with below code.
int main() { int nr; FILE *fp = fopen("/sd/PCE000.bin", "rb"); float read[1]; fread(read,sizeof(float),1,fp); pc.printf("\r\n %f",read[0]); fclose(fp); }I would like to know the formula for the conversion. Thank you.
posted by Mohan gandhi Vinnakota 14 Dec 2016It is working. It is little endien byte order.
while ((nr = fgetc(logFile)) !=EOF){ humicon[i] = nr; if (i == 3){ float x; const unsigned char bytes[] = {humicon[0],humicon[1],humicon[2],humicon[3]}; memcpy(&x, bytes, sizeof x); pc.printf("%f\n", x); i = 0;} else i++; }