How to convert 32 bit mantissa (IEEE754) to decimal number using Java? - 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?

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.

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.

Related

Java : Need to get the same functionality of the Integer.toHexString() with a String parameter and not an Int parameter due to NumberFormat Exception

I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.
Because:
The int data type is a 32-bit signed two's complement integer. It has
a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
Code Throwing the NumberFormatException:
String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?
Use BigInteger to avoid numeric limits of primitive int and long:
BigInteger x = new BigInteger("9999999999999999999999"); // Default radix is 10
String x16 = x.toString(16); // Radix 16 indicates hex
System.out.println(x16);
The class conveniently exposes a constructor that takes a String, which gets interpreted as a decimal representation of a number.
Demo.
If your input value can be arbitrarily large, then #dasblinkenlight's answer involving BigInteger is your best bet.
However, if your value is less than 263, then you can just use Long instead of Integer:
String dec = "9999999999";
String hex = Long.toHexString(Long.parseLong(dec));
System.out.println(hex); // 2540be3ff
Live demo.
Use Integer.parseUnsignedInt
When the number is above 2^31 but below 2^32, thus in the negative int range,
you can do:
int n = Integer.parseUnsignedInt("CAFEBABE", 16);
(I used hexadecimal here, as it is easier to see that above we are just in that range.)
However 9_999_999_999 is above the unsigned int range too.
Try this way:
String largeNumberAsAString = "9999999999";
System.out.println(Integer.toHexString(BigDecimal.valueOf(Double.valueOf(largeNumberAsAString)).intValue()));

Convert hexadecimal string to hexadecimal integer in java

I have hexadecimal String eg. "0x103E" , I want to convert it into integer.
Means String no = "0x103E";
to int hexNo = 0x103E;
I tried Integer.parseInt("0x103E",16); but it gives number format exception.
How do I achieve this ?
You just need to leave out the "0x" part (since it's not actually part of the number).
You also need to make sure that the number you are parsing actually fits into an integer which is 4 bytes long in Java, so it needs to be shorter than 8 digits as a hex number.
No need to remove the "0x" prefix; just use Integer.decode instead of Integer.parseInt:
int x = Integer.decode("0x103E");
System.out.printf("%X%n", x);

Exception while Parsing Hexadecimal to Short in Java

In file data.hex, the data is given in hexadecimal form where the first digit of hexadecimal number is always less than 8. Eg.
01FC 04BF 04C0 04C1 04C2 24C3 04C4 34C5 ...
To parse this file and store the values in shrt[] array i have written this code
void read_hex_short(String filename, short[] shrt, int x, int y) throws Exception
{
String str;
Scanner s=new Scanner(new BufferedReader(new FileReader(filename)));
for(int i=0;i<height*width;i++)
{
str= s.next(); // i have tried str="0x"+s.next() but it didn't work
image[i]=(short)Integer.parseInt(str);
}
s.close();
}
But i am getting NumberFormatException which arises while passing the first string i.e. 01FC only.
How can i parse these hexadecimal values and store them in the shrt[] array?
You should be using Integer.parseInt(str, 16) to tell it to use hex.
You should also be aware that any values greater than 0x7FFF will end up being negative in your array: Java doesn't have any unsigned numeric types (unless you count char).
You can use Short.parseShort(str, 16) to parse HEX. This will avoid the need to cast it to short from an int.
Give parseInt method a radix parameter. Like this:
Integer.parseInt(str, 16)

Parsing big hexadecimal numbers in Java

I'm trying to parse into int a String which is hexadecimal number in my code (FF00FF00, for example) using Integer.parseInt(String string, int radix), but always get NumberFormatException. If I parse the number without last two numbers (FF00FF) it works well.
Is there any method to parse such big numbers in Java?
If Integer is too small, use Long:
Long.parseLong(string, 16)
If Long is still too small, use BigInteger:
new BigInteger(string, 16)
I would use Long.parseLong(x, 16) BigInteger is overkill for a 32-bit value.
If you expect this value to be an int value you can cast the result.
int x = (int) Long.parseLong("FF00FF00", 16);

How can I convert an int number from decimal to binary?

How can I convert an int number from decimal to binary. For example:
int x=10; // radix 10
How can I make another integer has the binary representation of x, such as:
int y=1010; // radix 2
by using c only?
An integer is always stored in binary format internally -- saying that you want to convert int x = 10 base 10 to int y = 1010 base 2 doesn't make sense. Perhaps you want to convert it to a string representing the binary format of the integer, in which case you can use Integer.toBinaryString.
First thing you should understand is that a value is an abstract notion, that is not bounded to any representation. For example, if you have 20 apples, the number of apples will be the same regardless of the representation. So, dec("10") == bin("1010").
The value of an int reffers to this abstract notion of value, and it does not have any form until you with to print it. This means that the notion of base is important only for conversions from string to int and back.
String s = Integer.toBinaryString(10);
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html
Whether it's binary or decimal doesn't really have anything to do with the integer itself. Binary or decimal is a property of a physical representation of the integer, i.e. a String. Thus, the methods you should look at are Integer.toString() and Integer.valueOf() (the versions that take a radix parameter).
BTW, internally, all Java integers are binary, but literals in the source code are decimal (or octal).
Your question is a bit unclear but I'll do my best to try to make sense of it.
How can I make another integer has the binary representation of x such as: int y=1010 radix 2?
From this it looks like you wish to write a binary literal in your source code. Java doesn't support binary integer literals. It only supports decimal, hexadecimal and octal.
You can write your number as a string instead and use Integer.parseInt with the desired radix:
int y = Integer.parseInt("1010", 2);
But you should note that the final result is identical to writing int y = 10;. The integer 10 that was written as a decimal literal in the source code is identical in every way to one which was parsed from the binary string "1010". There is no difference in their internal representation if they are both stored as int.
If you want to convert an existing integer to its binary representation as a string then you can use Integer.toBinaryString as others have already pointed out.
Both integers will have the same interior representation, you can however display as binary via Integer.toBinaryString(i)
Use Integer.toBinaryString()
String y = Integer.toBinaryString(10);
Converting an integer to another base (string representation):
int num = 15;
String fifteen = Integer.toString(num, 2);
// fifteen = "1111"
Converting the string back into an integer
String fifteen = "1111";
int num = Integer.valueOf(fifteen, 2);
// num = 15
This covers the general case for any base. There's no way to explicitly assign an integer as binary (only decimal, octal, and hexadecimal)
int x = 255; // decimal
int y = 0377; // octal (leading zero)
int z = 0xFF; // hex (prepend 0x)

Categories