I have a char
array and need to convert it to convert it to float
.
I have two 16 bit values:
A = 7C37
B = 428B
and they need to be arranged like 42 8B 7C 37 to represent 69.743 in float but I have troubles to get there, I have tried the following:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main() {
char pData[8] = {0x00, 0x00, 0x00, 0x00, 0x7c, 0x37, 0x42, 0x8b};
float floatValue;
uint32_t raw;
raw = ((uint32_t)pData[5]) | (((uint32_t)pData[4])<< 8) |
(((uint32_t)pData[7])<<16) | (((uint32_t)pData[6])<<24);
// Copy the bytes in the correct order into the float variable
memcpy(&floatValue, &raw, sizeof(floatValue));
// Print the float value
printf("The float value is: %f\nThe raw value is 0x%x\n", floatValue, raw);
return 0;
}
.. but am confused as this unexpectedly produces the following output:
The float value is: -nan
The raw value is 0xff8b7c37
I assume the -nan
probably shows because of the 0xff in the left most Byte, it should be set to 0x42
, anyone can assist me with this?
UPDATE: I basically want to implement the Float - Big Endian (ABCD) from https://www.scadacore.com/tools/programming-calculators/online-hex-converter/ where 428B7C37 produces 69.74261
Once I got to squeeze the chars into a 32bit uint, it's as easy as:
#include <stdio.h>
union FloatIntUnion {
float f;
unsigned int i;
};
int main() {
union FloatIntUnion fiu;
fiu.i = 0x428B7C37; // Set the integer value
printf("%f\n", fiu.f); // Interpret the bit pattern as a float and print it
return 0;
}