Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java convert to int

Tags:

java

I am trying to convert to int like this, but I am getting an exception.

    String strHexNumber = "0x1";
    int decimalNumber = Integer.parseInt(strHexNumber, 16);
    Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)

It would be a great help if someone can fix it.

Thanks.

like image 984
user826323 Avatar asked May 02 '26 20:05

user826323


1 Answers

That's because the 0x prefix is not allowed. It's only a Java language thing.

String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);

If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.

int value = Integer.decode("0x12AF");
System.out.println(value);
like image 125
Adam Avatar answered May 05 '26 10:05

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!