当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。