當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Float toHexString()用法及代碼示例


Java Float 類的 toHexString() 方法返回一個與傳遞的參數(浮點參數)對應的十六進製字符串。

結果是:

  • 字符串 "NaN",如果傳遞的參數是 NaN。
  • 表示浮點參數的符號和絕對值(大小)的字符串。

用法:

public static String toHexStrng(float f)

參數:

f- 這是要轉換的浮點參數。

返回值:

toHexString() 方法返回浮點參數的十六進製字符串說明。

例子1

public class FloatToHexStringExample1 { 
    public static void main(String[] args) { 
        Float f1 =7823764.8374f;
        String f2 = Float.toHexString(f1);
        System.out.println("1. Hex String = "+f2);
        //passing negative numbers
        Float f3 = -6789564f;
        System.out.println("2. Hex String = "+Float.toHexString(f3));
        Float f4= 0.98822f;
        System.out.println("3. Hex String = "+Float.toHexString(f4));

    }
}

輸出:

1. Hex String = 0x1.dd8654p22
2. Hex String = -0x1.9e66fp22
3. Hex String = 0x1.f9f7f8p-1

例子2

public class FloatToHexStringExample2 {

    public static void main(String[] args) {

        Float f1 = Float.MIN_VALUE;

        String f2 = Float.toHexString(f1);

        System.out.println("1. "+f1+" converted to HexString = "+f2);


        Float f3 = Float.MAX_VALUE;

        String f4 = Float.toHexString(f3);

        System.out.println("2. "+f3+" converted to HexString = "+f4);


        Float f5 = Float.NaN;

        String f6 = Float.toHexString(f5);

        System.out.println("3. "+f5+" converted to HexString = "+f6);


        Float f7 = Float.POSITIVE_INFINITY;

        String f8 = Float.toHexString(f7);

        System.out.println("4. "+f7+" converted to HexString = "+f8);


        Float f9 = Float.NEGATIVE_INFINITY;

        String f10 = Float.toHexString(f9);

        System.out.println("5. "+f9+" converted to HexString = "+f10);

    }
}

輸出:

1. 1.4E-45 converted to HexString = 0x0.000002p-126
2. 3.4028235E38 converted to HexString = 0x1.fffffep127
3. NaN converted to HexString = NaN
4. Infinity converted to HexString = Infinity
5. -Infinity converted to HexString = -Infinity 

例子3

public class FloatToHexStringExample3 {

    public static void main(String[] args) {

        float f1 = 897.8f;

        Float f2 = new Float(f1);

        Float f3 = Float.toHexString(f2);

        System.out.println("Hex String = "+f3);

    }

}

輸出:

Error:(5, 37) java:incompatible types:java.lang.String cannot be converted to java.lang.Float






相關用法


注:本文由純淨天空篩選整理自 Java Float toHexString() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。