user3153014
user3153014

Reputation: 318

Convert hexadecimal string to hexadecimal integer in java

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 ?

Upvotes: 0

Views: 1567

Answers (2)

k314159
k314159

Reputation: 11072

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

Upvotes: 1

mhlz
mhlz

Reputation: 3547

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.

Upvotes: 2

Related Questions