0

I have hexadecimal String eg. "0x103E" , I want to convert it into integer. Means String no = "0x103E"; to int hexNo = 0x103E; I tried Integer.parseInt("0x103E",16); but it gives number format exception. How do I achieve this ?

3
  • 1
    possible duplicate of Convert hex string to int Commented Feb 27, 2015 at 11:25
  • Not a duplicate of the question linked to by @bot. Here, the issue is the extra 0x. In that other question, the issue was the size of the number being converted. Commented Feb 27, 2015 at 11:29
  • remove 0x from string Commented Feb 27, 2015 at 11:29

2 Answers 2

2

You just need to leave out the "0x" part (since it's not actually part of the number).

You also need to make sure that the number you are parsing actually fits into an integer which is 4 bytes long in Java, so it needs to be shorter than 8 digits as a hex number.

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

2 Comments

It's giving decimal representation of the number. I want hexadecimal int.
Integers are always binary. Converting them to a String again (even at the point where you're looking at it with your debugger) requires some base. The default for that is base 10. If you want to output the integer in base 16 again you need to use Integer.toString(i, 16) (as described here: docs.oracle.com/javase/8/docs/api/java/lang/… )
1

No need to remove the "0x" prefix; just use Integer.decode instead of Integer.parseInt:

int x = Integer.decode("0x103E");
System.out.printf("%X%n", x);

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.