There's another thread similar to this, but it is not a duplicate of this, so please don't mark it as such.
I have a communications simulation that takes test data - floats and ints - and converts them to Binary strings, then sends them across a pipe and they're picked-up by a listener at the other end. They're then 'unpacked' and converted back to numbers.
However, the conversion back using Integer.parseInt() throws an Exception, even though the Binary in the message is patently correctly formed IEEE-754 binary32 single-precision format.
float flt = -45732.9287f;
int intFloat = Float.floatToRawIntBits(flt);
String str = Integer.toBinaryString(intFloat);
System.out.println("------- Now do the Reverse -------");
int revint = Integer.parseInt(str, 2);
.... Throws java.lang.NumberFormatException: For input string: "11000111001100101010010011101110"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
Using parseInt() without a Radix throws a similar exception:
"int revint = Integer.parseInt(str);" throws an exception too, "java.lang.NumberFormatException: For input string: "11000111001100101010010011101110"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)".
So, it isn't merely a Radix usage issue.
Converting back using Long and BigInt would be incorrect because they are 64-bit IEEE-754 formats, meant for Signed Double, not signed Single Precision data types like Float.
I have a solution that fudges the asymetry in Java's conversion methods, but it strikes me as incongruous that there isn't a native API:
System.out.println("------- Now do the Reverse -------");
int revSign = str.substring(0,1).equals("1") ? -1: 1;
System.out.println("The passed-in sign is:"+revSign);
int revint = Integer.valueOf(str.substring(1), 2);
float revFloat = Float.intBitsToFloat(revint)*revSign;
I must be missing something.