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 ?
Asked
Active
Viewed 1,356 times
0

user3153014
- 308
- 1
- 4
- 16
-
1possible duplicate of [Convert hex string to int](http://stackoverflow.com/questions/11194513/convert-hex-string-to-int) – Chetan Kinger Feb 27 '15 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. – Dawood ibn Kareem Feb 27 '15 at 11:29
-
remove 0x from string – user1627167 Feb 27 '15 at 11:29
2 Answers
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
-
1Integers 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