store hex value (0x45E213) in an integer
Asked Answered
S

3

6

In my application I used a converter to create from 3 values > RGB-colors an Hex value. I use this to set my gradient background in my application during runtime.

Now is this the following problem. The result of the converter is a (String) #45E213, and this can't be stored in an integer. But when you create an integer,

int hex = 0x45E213;

it does work properly, and this doesn't give errors.

Now I knew of this, I Replaced the # to 0x, and tried it to convert from String to Integer.

int hexToInt = new Integer("0x45E213").intValue();

But now I get the numberFormatException, because while converting, it will not agree with the character E?

How can I solve this? Because I really need it as an Integer or Java/Eclipse won't use it in its method.

Stefan answered 17/3, 2012 at 11:6 Comment(0)
S
14

http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html

The Integer constructor with a string behaves the same as parseInt with radix 10. You presumably want String.parseInt with radix 16.

Integer.parseInt("45E213", 16)

or to cut off the 0x

Integer.parseInt("0x45E213".substring(2), 16);

or

Integer.parseInt("0x45E213".replace("0x",""), 16);
Sailcloth answered 17/3, 2012 at 11:9 Comment(3)
I guess you mean Integer.parseInt("45E213");. You would need to strip 0x from the StringMononuclear
Thanks for the ParseInt idea, and the fast reply, it worked. only my background isn't changing color, but that would be an other fix.Stefan
You have and extra closing parenthesis in both Integer.parseInt functions.Nantucket
P
7

The lesser known Integer.decode(String) might be useful here. Note it will also do leading zeros as octal, which you might not want, but if you're after something cheap and cheerful...

int withHash = Integer.decode("#45E213");
System.out.println(Integer.toHexString(withHash));

int withZeroX = Integer.decode("0x45E213");
System.out.println(Integer.toHexString(withZeroX));

Output

45e213
45e213
Polemics answered 17/3, 2012 at 11:23 Comment(0)
P
4

This Method accepts your String you can use Color.parseColor(String) but you need to replace 0x prefix with #

Pothunter answered 17/3, 2012 at 11:12 Comment(1)
This would be helpfull if i need Colors to set the background, and this is when i just need 1 solid color, but i need to create a gradient background, and therefor you need two heximals.Stefan

© 2022 - 2024 — McMap. All rights reserved.