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 ?

user3153014
  • 308
  • 1
  • 4
  • 16

2 Answers2

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.

mhlz
  • 3,497
  • 2
  • 23
  • 35
  • It's giving decimal representation of the number. I want hexadecimal int. – user3153014 Feb 27 '15 at 11:46
  • 1
    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: http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#toString-int-int- ) – mhlz Feb 27 '15 at 12:26
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);
k314159
  • 5,051
  • 10
  • 32