[英]Java: How to convert a String of Binary values to a Float and vice-versa?
如何将12345.12346f的浮点值转换为二进制值的字符串,即“0011010101010101”,反之亦然?
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);
For signed Floats, use Long or BigInteger to parse the string. 对于签名的Floats,使用Long或BigInteger来解析字符串。 Casting by int causes the digit at first of 32 bits be intepreted as sign digit.
按int进行转换会导致32位首先的数字被解释为符号数字。 procedure :
程序:
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);
Working sample: 工作样本:
class F {
public static void main( String ... args ) {
System.out.println(
Integer.toBinaryString(
Float.floatToIntBits(12345.12346f)
)
);
}
}
Output: 输出:
1000110010000001110010001111110
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'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.