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.
Sure – you need to get rid of the “0x” part if you want to use
parseInt:If you know your value will start with “0x” you can just use:
Otherwise, just test for it:
Note that you should think about how negative numbers will be represented too.
EDIT: Adam’s solution using
decodewill certainly work, but if you already know the radix then IMO it’s clearer to state it explicitly than to have it inferred – particularly if it would surprise people for “035” to be treated as octal, for example. Each method is appropriate at different times, of course, so it’s worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.