I am trying to convert this Hex Value C2DE70A4 in Android. This is the Code that I am writing for Conversion:
try {
String hexString = "C2DE70A4";
float myFloat = Float.intBitsToFloat(Integer.parseInt(hexString, 16));
}
catch (Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
But it is causing an Exception and telling me that Invalid int: "C2DE70A4"
Can anyone help me to make the Conversion? The Float value should be: -111.22
Thanks.
0xC2DE70A4 in decimal is 3,269,357,732, but an int's max value is 2,147,483,647. That's why you can't parse it -- the parsed value is too big to fit in an int.
You should parse the string as a long, then cast it to an int , and finally call Float.intBitsToFloat on that:
long asLong = Long.parseLong(hexString, 16);
int asInt = (int) asLong;
float myFloat = Float.intBitsToFloat(asInt);
// or, just
float myFloat = Float.intBitsToFloat((int)Long.parseLong(hexString, 16));
Detailed explanation:
Fundamentally, the problem is that C2DE70A4 represents an unsigned value, whereas ints in Java are signed. If you parse it as a long and then look at its bits (via Long.toBinaryString), you'll see:
11000010110111100111000010100100
That's a 32-length string, because toBinaryString omits leading 0s. So why didn't it fit in a 32-bit int? Because that binary string above represents an unsigned number. Or, more precisely, it's really shorthand for this signed, 64-bit, two's complement number:
0000000000000000000000000000000011000010110111100111000010100100
... which equals 3269357732 in decimal, which is out of the range of an int because an int is signed, meaning that the leftmost digit is the sign and not part of the number's magnitude (aka how "big" it is).
If you take that long and cast it to an int, it'll discard the leftmost 32 digits, leaving you with a 32-bit int 11000010110111100111000010100100 -- which corresponds to -1025609564 in decimal (again, in two's complement). If you then take that number and feed it to intBitsToFloat, you'll get -111.22.
change the hex string to 0xC2DE70A4..
public class Test {
public static void main (String[] args) {
String myString = "BF800000";
Long i = Long.parseLong(myString, 16);
Float f = Float.intBitsToFloat(i.intValue());
System.out.println(f);
System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
}
}
Related
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()));
I was wondering if it's possible to convert a signed Hexadecimal (negative) to its corresponding decimal value.
I assume that you have a hexadecimal value in form of a String.
The method parseInt(String s, int radix) can take a hexadecimal (signed) String and with the proper radix (16) it will parse it to an Integer.
int decimalInt = parseInt(hexaStr, 16);
the solution above only works if you have numbers like -FFAA07BB... if you want the Two's complements you'll have to convert it yourself.
String hex = "F0BDC0";
// First convert the Hex-number into a binary number:
String bin = Integer.toString(Integer.parseInt(hex, 16), 2);
// Now create the complement (make 1's to 0's and vice versa)
String binCompl = bin.replace('0', 'X').replace('1', '0').replace('X', '1');
// Now parse it back to an integer, add 1 and make it negative:
int result = (Integer.parseInt(binCompl, 2) + 1) * -1;
or if you feel like having a one-liner:
int result = (Integer.parseInt(Integer.toString(Integer.parseInt("F0BDC0", 16), 2).replace('0', 'X').replace('1', '0').replace('X', '1'), 2) + 1) * -1;
If the numbers get so big (or small), that an Integer will have an overflow, use Long.toString(...) and Long.parseLong(...) instead.
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.
I got an exception while parsing a string to byte
String Str ="9B7D2C34A366BF890C730641E6CECF6F";
String [] st=Str.split("(?<=\\G.{2})");
byte[]bytes = new byte[st.length];
for (int i = 0; i <st.length; i++) {
bytes[i] = Byte.parseByte(st[i]);
}
That's because the default parse method expects a number in decimal format, to parse hexadecimal number, use this parse:
Byte.parseByte(st[i], 16);
Where 16 is the base for the parsing.
As for your comment, you are right. The maximum value of Byte is 0x7F. So you can parse it as int and perform binary AND operation with 0xff to get the LSB, which is your byte:
bytes[i] = Integer.parseInt(st[i], 16) & 0xFF;
Assuming you want to parse the string as hexadecimal, try this:
bytes[i] = Byte.parseByte(st[i], 16);
The default radix is 10, and obviously B is not a base-10-digit.
Java is very picky on signedness, it will not accept values to overflow. Thus, if you parse a Byte and it is larger than 127 (for example, 130 dec or 83 hex) you will get a NumberFormatException. Same happens if you parse an 8 digit hex number as an Integer (or a 16 digit hex number as a Long) and it starts with 8-F. Such values will not be interpreted as negative (two's complement) but as illegal.
If you think that this is anal retentive, I totally agree. But that's Java style.
To parse hex values as two's complement numbers either use a large enough integer type (for example, if you are parsing a Byte use Integer instead and type cast it to a byte later) or -- if you need to parse a Long, split the number in half it is 16 digits, then combine. Here's an example:
public static long longFromHex(String s) throws IllegalArgumentException {
if (s.length() == 16)
return (Long.parseLong(s.substring(0,8),16)<<32)|(Long.parseLong(s.substring(8,16),16)&0xffffffffL);
return Long.parseLong(s, 16);
}
Or, to read a Byte, just use Integer instead:
public static byte byteFromHex(String s) throws IllegalArgumentException {
int i = Integer.parseInt(s, 16);
if (i < 0 || i > 255) throw new IllegalArgumentException("input string "+s+" does not fit into a Byte");
return (byte)i;
}
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)