java.lang.NumberFormatException when converting a Hex String to Int - java

I want to convert a Hex String to decimal, but I got an error in the following code:
String hexValue = "23e90b831b74";
int i = Integer.parseInt(hexValue, 16);
The error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "23e90b831b74"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)

23e90b831b74 is too large to fit in an int.
You can easily see that by counting the digits. Each two digits in a hex number requires a single byte, so 12 digits require 6 bytes, while an int only has 4 bytes.
Use Long.parseLong.
String hexValue = "23e90b831b74";
long l = Long.parseLong(hexValue, 16);

Related

convert hexadecimal number to binary

int hex=Integer.parseInt(str.trim(),16);
String binary=Integer.toBinaryString(hex);
i have a array of hexadecimal numbers as strings and i want to convert those numbers to binary string, above is the code i used and in there, i get a error as shown below
Exception in thread "main" java.lang.NumberFormatException: For input string: "e24dd004"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at sew1.javascript.main(javascript.java:20)
Maximum Integer in Java is 0x7fffffff, because it is signed.
Use
Long.parseLong(str.trim(),16);
or
BigInteger(str.trim(),16);
instead.
The problem is that e24dd004 is larger than int can handle in Java. If you use long, it will be fine:
String str = "e24dd004";
long hex = Long.parseLong(str.trim(),16);
String binary=Long.toBinaryString(hex);
System.out.println(binary);
That will be valid for hex up to 7fffffffffffffff.
An alternative, however, would be to do a direct conversion of each hex digit to 4 binary digits, without ever converting to a numeric value. One simple way of doing that would be to have a Map<Character, String> where each string is 4 digits. That will potentially leave you with leading 0s of course.
Use BigInteger as below:
BigInteger bigInteger = new BigInteger("e24dd004", 16);
String binary = bigInteger.toString(2);
Or using Long.toBinaryString() as below:
long longs = Long.parseLong("e24dd004",16);
String binary = Long.toBinaryString(longs);
Since java-8, you can treat integers as unsigned, so you could do:
String str = "e24dd004";
int i = Integer.parseUnsignedInt(str, 16);
String binary = Integer.toBinaryString(i); //11100010010011011101000000000100
String backToHex = Integer.toUnsignedString(i, 16); //e24dd004
You would be able to handle values that are not larger than 2^32-1 (instead of 2^31-1 if you use signed values).
If you can't use it, you'll have to parse it as a long like other answers showed.

how to use bytes in java?

Why does this code return 221 here? What is the logic behind this? How this working? Please explain this to me for I am new to Java.
import java.io.UnsupportedEncodingException;
public class Checksrting {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
byte[] byteArray = new byte[2];
byteArray[0] = 100;
byteArray[1] = 100;
Long ID = null;
try {
ID = Long.parseLong(new String(byteArray, "utf-8").trim(), 16);
System.out.print(ID);
} catch (NumberFormatException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So please explain to me what is the use of utf-8 and ,16?
100 is the equivalent of the d character. So your string will become dd.
When you do
ID = Long.parseLong(new String(byteArray, "utf-8").trim(), 16);
You are converting the string to a long number, with hexadecimal format.
the decimal value for dd is 221, that's why you get that output.
what is the use of utf-8 and ,16?
utf-8 is the character encoding that the String constructor will use to build up the string, and 16 is the radix that will be used to convert your string to a long.
As you can see in the documentation String constructor gets a parameter charset:
Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
And the 16 is the radix which is to use for the conversion:
See the documentation from Long
It returns 221 because of the conversion of dd string to hexadecimal number.
new String(byteArray, "utf-8").trim();
With this statement byteArray[0] contains 100 which is converted to character its representation is 'd' as there are 2 elements in the byteArray therefore it creates the String 'dd' and converts the String into the hexadecimal code.
new String(byteArray, "utf-8").trim();
returns 'dd'
then it is parsed into the Long value as the regEx parameter is given 16, therefore it converts into hexadecimal format i.e; 221
Long.parseLong("dd",16);
"utf-8" is the character encoding, i.e. how a String is represented as bytes.
UTF-8 uses a variable length encoding, and ASCII characters can be represented as a single byte with 0 as highest bit. This is the case for d which is represented as 100 (in decimal notation). Since you have 2 bytes with the number 100, this translates to the string "dd"
16 is the radix used for conversion from String to Long, so this translates from strings in hex notation.
A d in hex notation is 13 in decimal notation. So dd becomes 13 * 16 + 13 = 208 + 13 = 221
I agree with the older answers, but am adding some advice on how to figure out this sort of issue.
First, if you are having trouble understanding a complicated expression, extract sub-expressions into local variables, and print those variables:
String s1 = new String(byteArray, "utf-8");
System.out.println("s1: |" + s1 + "|");
String s2 = s1.trim();
System.out.println("s2: |" + s2 + "|");
ID = Long.parseLong(s2, 16);
System.out.print(ID);
It now prints:
s1: |dd|
s2: |dd|
221
Next, look at the individual sub-expressions. If there is anything you do not understand about a call and what it did, look it up in the API documentation.
For example, you asked about the "16". The Long.parseLong(String s, int radix) documentation says: "Parses the string argument as a signed long in the radix specified by the second argument. ". The output from the modified program shows that s is "dd", so it is going to parse "dd" as a hexadecimal number. A programmer's calculator will show you that hex "dd" is decimal 221.

Java: Convert a hexadecimal encoded String to a hexadecimal byte

An Item-ID in hexadecimal and the amount in decimal has to be entered in two JTextFields.
Now I have to convert the Item ID hexadecimal encoded in a String to a byte hexadecimal.
String str = itemIdField.getText(); // Would be, for example, "5e"
byte b = // Should be 0x5e then.
So if str = "5e", b = 0x5e
if str = "6b" b = 0x6b and so on.
Does anybody now, what the code to convert that would be then?
Google doesn't know, it thinks, I want to convert the text to a byte[]
Thank you, Richie
You can use Byte.parseByte(str, 16), that will return the byte value represented by the hexadecimal value in str.

Big Integer and Hex Strings in java

I am trying to convert a hex string to a decimal value (integer). Having found
int i = Integer.valueOf(s, 16).intValue();
here,
i achieved to convert a hex string up to a certain size to an int.
But when the string gets larger, then the int or long does not work, so i tried BigInteger.
Unfortunately, it returns an error :
JEncrytion.java:186: <identifier> expected
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
JEncrytion.java:186: illegal start of expression
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
JEncrytion.java:186: not a statement
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
The code fragment is :
String[] parts = final_key.split("#") ;
String part_fixed = parts[0];
String part_user = parts[1];
BigInteger part_user_hex = Integer.valueOf("45ffaaaaa", 16).int();
System.out.println("");
System.out.println("hex value of the key : " + part_user_hex);
Any ideas what to do?
3 errors
You're trying to assign a primitive int value to a BigInteger reference variable. That won't work. You want to do
BigInteger hex = new BigInteger("45ffaaaaa", 16);
Also, you've named your class JEncrytion instead of JEncryption.

Hex to binary conversion java

I have the following code
temp = "0x00"
String binAddr = Integer.toBinaryString(Integer.parseInt(temp, 16));
Why do I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "0x00"
Since the string contains 0x, use Integer.decode(String nm):
String binAddr = Integer.toBinaryString(Integer.decode(temp));
Because the leading 0x is not part of a valid base-16 number -- it's just a convention to indicate to a reader that a number is in hex.
Get rid of the '0x': from the javadocs:
The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned.
BigInteger.toString(radix) will solve this issue
Refer method description
Hope it helps.
The 0x is for integer literals, eg:
int num = 0xCAFEBABE;
but is not a parseable format. Try this:
temp = "ABFAB"; // without the "0x"
String binAddr = Integer.toBinaryString(Integer.parseInt(temp, 16));

Categories

Resources