Store hex value (0x45E213) in integer

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

Now this is the next problem. The result of the conversion is (String) #45E213, and it cannot be stored as an integer. But when you create an integer,

int hex = 0x45E213;

It works correctly and it does not give errors.

Now I knew about it, I replaced it #with 0xand tried to convert it from String to Integer.

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

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

How can i solve this? Since I really need it, because Integer or Java / Eclipse will not use it in their method.

+5
source share
3 answers

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. Suppose you want String.parseInt with radix 16.

Integer.parseInt("45E213", 16)

or cut off 0x

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

or

Integer.parseInt("0x45E213".replace("0x",""), 16);
+12
source

The lesser-known Integer.decode (String) may be useful here. Please note that this will also lead to leading zeros being eighths, which you may not like, but if you are after something cheap and fun ...

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
+7
source

Color.parseColor(String), 0x #

+4

All Articles