Reputation: 5707
This is a simplified C++ program converting 4 bytes into their IEE754 float representation.
#include <iostream>
#include <math.h>
#include <memory.h>
uint8_t bytes[4] = {0x40, 0xd5, 0xc6, 0x7f}; // 0x40d5c67f
float f;
int main()
{
memcpy(&f, &bytes[0], 4);
printf("%.*lf", 5, f);
}
it's output is nan
! isnan
also returns true for it. How has this happened? 0x40d5c67f is 6.6804...
Happens both on my arduino-like microcontroller and http://cpp.sh/
Upvotes: 0
Views: 279
Reputation: 75062
If you are running this code on a machine that uses little-endian, higher digits of multi-byte numbers are stored in higher address of the memory.
Therefore, on little endian machines, the 4-byte number on memory
0x40, 0xd5, 0xc6, 0x7f
is treated as 0x7fc6d540
, not 0x40d5c67f
.
Interpreting as IEEE754, the exponent part of this number is 255 and the fraction part of this number is not 0, so this is NaN.
Upvotes: 5