如何转换十六进制字符串在Java中浮动? [英] How to convert hex string to float in Java?

查看:250
本文介绍了如何转换十六进制字符串在Java中浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将十六进制字符串转换为Java中的单精度浮点数?



例如,如何实现:

float f = HexStringToFloat(BF800000); // f现在应该包含-1.0



我问这个,因为我试过了:

  float f =(float)( -  1.0); 
String s = String.format(%08x,Float.floatToRawIntBits(f));
f = Float.intBitsToFloat(Integer.valueOf(s,16).intValue());

但我得到以下例外:

java.lang.NumberFormatException:对于输入字符串:bf800000

解决方案

  public class测试{
public static void main(String [] args){

String myString =BF800000;
Long i = Long.parseLong(myString,16);
Float f = Float.intBitsToFloat(i.intValue());
System.out.println(f);
System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
}
}


How to convert hexadecimal string to single precision floating point in Java?

For example, how to implement:

float f = HexStringToFloat("BF800000"); // f should now contain -1.0

I ask this because I have tried:

float f = (float)(-1.0);
String s = String.format("%08x", Float.floatToRawIntBits(f));
f = Float.intBitsToFloat(Integer.valueOf(s,16).intValue());

But I get the following exception:

java.lang.NumberFormatException: For input string: "bf800000"

解决方案

public class Test {
  public static void main (String[] args) {

        String myString = "BF800000";
        Long i = Long.parseLong(myString, 16);
        Float f = Float.intBitsToFloat(i.intValue());
        System.out.println(f);
        System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
  }
}

这篇关于如何转换十六进制字符串在Java中浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆