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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
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 …

710 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