Solved

Parsing a hex string into an integer?

Posted on 2011-03-20
5
454 Views
Last Modified: 2012-05-11
Hi,

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.

Thanks
0
Comment
Question by:DJ_AM_Juicebox
  • 4
5 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35177846
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35177864
You should remove 0x part
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35177866

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

output:
num: 267526690

Open in new window

0
 
LVL 47

Accepted Solution

by:
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
0
 
LVL 92

Expert Comment

by:objects
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.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

762 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

22 Experts available now in Live!

Get 1:1 Help Now