C++ NaN byte representation changes during assignm

2020-07-06 05:25发布

问题:

In trying to assign a NaN to a variable on an x64 processor

*dest = *(float*)&sourceNaN;

where

unsigned char sourceNaN[] = {00,00, 0xa0, 0x7f};

The floating point instructions fld and fstp (seen in the disassembly) change the 0xa0 byte to an 0xe0. Thus the destination has an extra bit set. Can someone explain why this is happening? This is a Windows application.

The assembly language code:

005C9B9C  mov         eax,dword ptr [ebp+10h]  
005C9B9F  fld         dword ptr [ebp-80h]  
005C9BA2  fstp        dword ptr [eax] 

回答1:

0x7fa00000 is a signalling NaN ("sNaN"). 0x7fe00000 is a quiet NaN ("qNaN"). I haven't heard of this behavior under x86, but under ARM sNaNs get converted to the corresponding qNaNs when used in operations, alongside raising an FP exception (which is normally ignored). It looks like the same thing is happening here.

The good news is, they're both NaNs. Unless you're specifically relying on the signalling behavior, everything's going right.