Problems casting NAN floats to int

后端 未结 3 2107
不思量自难忘°
不思量自难忘° 2021-01-17 08:30

Ignoring why I would want to do this, the 754 IEEE fp standard doesn\'t define the behavior for the following:

float h = NAN;
printf(\"%x %d\\n\", (int)h, (         


        
3条回答
  •  醉酒成梦
    2021-01-17 09:03

    There is a reason for this behavior, but it is not something you should usually rely on.

    As you note, IEEE-754 does not specify what happens when you convert a floating-point NaN to an integer, except that it should raise an invalid operation exception, which your compiler probably ignores. The C standard says the behavior is undefined, which means not only do you not know what integer result you will get, you do not know what your program will do at all; the standard allows the program to abort or get crazy results or do anything. You probably executed this program on an Intel processor, and your compiler probably did the conversion using one of the built-in instructions. Intel specifies instruction behavior very carefully, and the behavior for converting a floating-point NaN to a 32-bit integer is to return 0x80000000, regardless of the payload of the NaN, which is what you observed.

    Because Intel specifies the instruction behavior, you can rely on it if you know the instruction used. However, since the compiler does not provide such guarantees to you, you cannot rely on this instruction being used.

提交回复
热议问题