Parsing a hex string into an integer?

Posted on 2011-03-20
Last Modified: 2012-05-11

What's the correct way to parse a hex integer string?:

    String str = "0xFF222222";
    int val = Integer.parseInt(str, 16);

The above throws a number format exception.

Question by:DJ_AM_Juicebox
  • 4
LVL 47

Expert Comment

ID: 35177846
LVL 47

Expert Comment

ID: 35177864
You should remove 0x part
LVL 47

Expert Comment

ID: 35177866

            String hex = "FF22222";
                    long num = Long.parseLong(hex,16);
      System.out.println("num: " + num);

num: 267526690

Open in new window

LVL 47

Accepted Solution

for_yan earned 500 total points
ID: 35177872

That is exactly your number:

 String hex = "FF222222";
                    long num = Long.parseLong(hex,16);
      System.out.println("num: " + num);

num: 4280427042
LVL 92

Expert Comment

ID: 35178075
When parsing a hex string you need to remove the 0x from the string as for_yan has mentioned above.
The 0x is not part of the actual hex value you are parsing.

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
create a gui in perl 3 72
micro services spring boot application error 3 148
eclipse java  build path 6 45
even odd program using while loop 3 29
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now