TransWikia.com

C++ printing float as nan

Stack Overflow Asked by ACarter on January 14, 2021

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/

One Answer

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.

Correct answer by MikeCAT on January 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP