store hex value (0x45E213) in an integer

25,899

Solution 1

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);

Solution 2

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

Solution 3

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

Share:
25,899
Dion Segijn
Author by

Dion Segijn

Dion Segijn, from The Netherlands

Updated on May 26, 2020

Comments

  • Dion Segijn
    Dion Segijn almost 4 years

    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.