Java:如何将二进制值的字符串转换为浮点数,反之亦然?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5157664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:44:41  来源:igfitidea点击:

Java: How to convert a String of Binary values to a Float and vice-versa?

javafloating-pointbytearraytype-conversion

提问by okami

How do I convert the float value of 12345.12346f to a String of binary values, i.e. "0011010101010101", and vice-versa?

如何将 12345.12346f 的浮点值转换为二进制值的字符串,即“0011010101010101”,反之亦然?

回答by krtek

I'm not sure it is what you want, but here's a solution to have the binary representation of the IEEE 754 floating-point "double format" bit layout for a float (it is basically the memory representation of a float) :

我不确定它是否是您想要的,但这里有一个解决方案,可以将 IEEE 754 浮点“双格式”位布局的二进制表示用于浮点数(它基本上是浮点数的内存表示):

int intBits = Float.floatToIntBits(yourFloat); 
String binary = Integer.toBinaryString(intBits);

For the reverse procedure :

对于相反的过程:

int intBits = Integer.parseInt(myString, 2);
float myFloat = Float.intBitsToFloat(intBits);

回答by OscarRyz

Working sample:

工作样本:

class F { 
  public static void main( String ... args ) { 
    System.out.println(
          Integer.toBinaryString( 
             Float.floatToIntBits(12345.12346f)
          ) 
     );
  }
}

Output:

输出:

1000110010000001110010001111110

回答by snow

For signed Floats, use Long or BigInteger to parse the string. Casting by int causes the digit at first of 32 bits be intepreted as sign digit. procedure :

对于有符号浮点数,使用 Long 或 BigInteger 来解析字符串。通过 int 进行转换会导致 32 位中的第一个数字被解释为符号数字。程序 :

int intBits = Float.floatToIntBits(yourFloat); 
String binary = Integer.toBinaryString(intBits);

reverse procedure :

反向程序:

int intBits = new BigInteger(myString, 2).intValue();
// int intBits = (int) Long.parseLong(myString, 2);
float myFloat = Float.intBitsToFloat(intBits);

回答by DJClayworth

You can get the bit representation of a Java Float value using

您可以使用以下方法获取 Java Float 值的位表示

Float.floatToIntBits(float f);

Once you have done that you can test each bit of the resulting int in turn, starting with the highest, and find out if it set, writing a '1' if it is set and a '0' if not.

完成后,您可以依次测试结果 int 的每一位,从最高的开始,并找出它是否已设置,如果已设置则写入“1”,如果未设置则写入“0”。