How do I parse a hex-int from a string to an Integer?

0

I have no problem in writing this: (it also doesn't give any errors)

int hex = 0xFFFFFFFF;

The integer has to have an alpha value also!

But when I try to do this:

Integer hex = Integer.parseInt("0xFFFFFFFF");
// Or I try this:
Integer hex = Integer.parseInt("FFFFFFFF");

I get a java.lang.NumberFormatException: For input string: "0xFFFFFFFF" thrown!

Why is this not working?

I'm guessing that there is some other way to parse hex integers that I am just not realizing, and I really need to be able to parse hex from string for a program I am making.

java
parsing
integer
asked on Stack Overflow Nov 21, 2014 by bernhardkiv

1 Answer

1

There is actually a separate function where you can define the radix:

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)

Integer.parseInt(x) simply calls Integer.parseInt(x, 10), so you have to specify a radix 10 number.

In order to parse a hex string, you would simply have to use the following (note that the 0x prefix is not allowed):

Integer.parseInt("FFFFFFF", 16);
answered on Stack Overflow Nov 21, 2014 by (unknown user) • edited Oct 18, 2018 by Lii

User contributions licensed under CC BY-SA 3.0