Sachithra Sewwandi
Sachithra Sewwandi

Reputation: 303

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)

Upvotes: 2

Views: 1775

Answers (4)

Alexis C.
Alexis C.

Reputation: 93892

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.

Upvotes: 0

Dmitry
Dmitry

Reputation: 2149

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

Use

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

or

BigInteger(str.trim(),16);

instead.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503839

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.

Upvotes: 1

SMA
SMA

Reputation: 37103

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

Upvotes: 0

Related Questions