📜  Java中的浮点 floatToRawIntBits() 方法及示例

📅  最后修改于: 2022-05-13 01:54:48.702000             🧑  作者: Mango

Java中的浮点 floatToRawIntBits() 方法及示例

Float Class中的floatToRawIntBits()方法是Java中的内置函数,它根据 IEEE 754 浮点“单一格式”位布局返回指定浮点值的表示,保留 Not-a-Number (NaN ) 值。

句法:

public static int floatToRawIntBits(float val)

参数:该方法只接受一个指定浮点数的参数val

返回值:该函数返回表示浮点数的位。但是有3种特殊情况:

  • 如果参数为正无穷大,则结果为0x7f800000
  • 如果参数为负无穷大,则结果为0xff800000
  • 如果参数为NaN ,则结果为0x7fc00000

下面的程序说明了Float.floatToRawIntBits()方法的使用:

方案一:

// Java program to demonstrate
// Float.floatToRawIntBits() method
import java.lang.*;
  
class Gfg1 {
  
    public static void main(String args[])
    {
  
        float val = 1.5f;
  
        // function call
        int answer = Float.floatToRawIntBits(val);
  
        // print
        System.out.println(val + " in raw int bits: "
                           + answer);
    }
}
输出:
1.5 in raw int bits: 1069547520

方案二:

// Java program to demonstrate
// Float.floatToRawIntBits() method
  
import java.lang.*;
  
class Gfg1 {
  
    public static void main(String args[])
    {
  
        float val = Float.POSITIVE_INFINITY;
        float val1 = Float.NEGATIVE_INFINITY;
        float val2 = Float.NaN;
  
        // function call
        int answer = Float.floatToRawIntBits(val);
  
        // print
        System.out.println(val + " in raw int bits: "
                           + answer);
  
        // function call
        answer = Float.floatToRawIntBits(val1);
  
        // print
        System.out.println(val1 + " in raw int bits: "
                           + answer);
  
        // function call
        answer = Float.floatToRawIntBits(val);
  
        // print
        System.out.println(val2 + " in raw int bits: "
                           + answer);
    }
}
输出:
Infinity in raw int bits: 2139095040
-Infinity in raw int bits: -8388608
NaN in raw int bits: 2139095040

参考: https: Java/lang/Float.html#floatToRawIntBits(float)