繁体   English   中英

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

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

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

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

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

对于相反的程序:

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

对于签名的Floats,使用Long或BigInteger来解析字符串。 按int进行转换会导致32位首先的数字被解释为符号数字。 程序:

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

逆过程:

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

工作样本:

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

输出:

1000110010000001110010001111110

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

Float.floatToIntBits(float f);

完成后,你可以依次测试结果int的每一位,从最高位开始,找出是否设置,如果设置则写'1',否则写'0'。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM