2
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)

4 Answers 4

3

Maximum Integer in Java is 0x7fffffff, because it is signed.

Use

Long.parseLong(str.trim(),16);

or

BigInteger(str.trim(),16);

instead.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

thnx for helping its k now
0

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);

Comments

0

Since , 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.