5

I have a file with many hex numbers (for eg - 0X3B4 ). Im trying to parse this file as assign these numbers to integers, but dont seem to get Integer.parseInt to work.

   int testint = Integer.parseInt("3B4",16);  <- WORKS

   int testint = Integer.parseInt("0X3B4",16);

gives error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "0x3b4"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

What is the right way to assign the value 0XB4 to an int ?

Do I have to get rid of the 0X - its not unusual to represent hex nos this way...

Nikhil
  • 797
  • 6
  • 12
  • 30

1 Answers1

8

You can do

int hex = Integer.decode("0x3b4");

You are right that parseInt and parseLong will not accept 0x or 0X

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130