razshan
razshan

Reputation: 1138

How to convert 32 bit mantissa (IEEE754) to decimal number using Java?

I have this for example:

0 10000101 00111100000000000000000

and want to convert this to decimal number.

So far, I already have the code to get the exponent part:

String[]hex={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
 String[]binary={"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};

String userInput="429E0000";
 String result="";
 for(int i=0;i<userInput.length();i++)
 {
  char temp=userInput.charAt(i);
  String temp2=""+temp+"";
  for(int j=0;j<hex.length;j++)
  {
   if(temp2.equalsIgnoreCase(hex[j]))
   {
    result=result+binary[j];
   }
  }
 }
 System.out.println(result);

    int exponent = Integer.parseInt(result.substring(1,9),2)-127;
    System.out.println(exponent);

Is there any in-built command in Java?

Upvotes: 2

Views: 4460

Answers (2)

Stephen C
Stephen C

Reputation: 718768

The Integer.ParseInteger(str, radix) will convert a binary digit string to an int ... if you use two as the radix.

However, Daniels answer gives you a better approach that avoids the need for any intermediate string representation of the number.

Upvotes: 2

Daniel Fischer
Daniel Fischer

Reputation: 183868

Yes, there is a built-in command, intBitsToFloat converts a 32-bit int to a float. You only have to parse your input as an int, the easier way - if your input is in hexadecimal format - would be to directly use base 16 in Integer.parseInt(), then intBitsToFloat converts that bit pattern to a float.

Upvotes: 10

Related Questions