Solved

Parsing a hex string into an integer?

Posted on 2011-03-20
5
462 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

Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
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.

832 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