Are the bit patterns of NaNs really hardware-dependent?

前端 未结 4 646
臣服心动
臣服心动 2020-12-01 08:52

I was reading about floating-point NaN values in the Java Language Specification (I\'m boring). A 32-bit float has this bit format:

seee eeee em         


        
4条回答
  •  孤街浪徒
    2020-12-01 09:35

    Here is a program demonstrating different NaN bit patterns:

    public class Test {
      public static void main(String[] arg) {
        double myNaN = Double.longBitsToDouble(0x7ff1234512345678L);
        System.out.println(Double.isNaN(myNaN));
        System.out.println(Long.toHexString(Double.doubleToRawLongBits(myNaN)));
        final double zeroDivNaN = 0.0 / 0.0;
        System.out.println(Double.isNaN(zeroDivNaN));
        System.out
            .println(Long.toHexString(Double.doubleToRawLongBits(zeroDivNaN)));
      }
    }
    

    output:

    true
    7ff1234512345678
    true
    7ff8000000000000
    

    Regardless of what the hardware does, the program can itself create NaNs that may not be the same as e.g. 0.0/0.0, and may have some meaning in the program.

提交回复
热议问题