Search code examples
javadecimalieee

Want to convert a 32 bit IEEE String to decimal in Java.


I'm trying to convert a 32 digit String to a decimal...

Example: "00111111100000000000000000000000" > 1 and "01000001101000000000000000000000" > 20

I'm trying the below code but the result I'm getting is totally wrong. "00111111100000000000000000000000" > 2147483647

    String s = "00111111100000000000000000000000"
    float fl = Float.parseFloat(s);
    int bits = Math.round(Math.abs(fl));
    decTextView.setText(Long.toString(bits));

Any advise?


Solution

  • You need to do three things.

    • Read the 0s and 1s in the String as an int.
    • Use intBitsToFloat to convert the int to a float.
    • Convert the float to a decimal (BigDecimal).

    .

    int bits = Integer.parseInt(s,2);
    float value = Float.intBitsToFloat(bits);
    BigDecimal asDecimal = BigDecimal.valueOf(value);