user2761225
user2761225

Reputation: 5

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"

Upvotes: 0

Views: 4946

Answers (5)

Bohemian
Bohemian

Reputation: 424993

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

Upvotes: 0

Ashish
Ashish

Reputation: 745

BigInteger.toString(radix) will solve this issue

Refer method description

Hope it helps.

Upvotes: 0

user484261
user484261

Reputation:

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.

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53819

Since the string contains 0x, use Integer.decode(String nm):

String binAddr = Integer.toBinaryString(Integer.decode(temp));

Upvotes: 1

Thorn G
Thorn G

Reputation: 12766

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.

Upvotes: 0

Related Questions