stijnb1234
stijnb1234

Reputation: 184

Java - Convert a HEX color to a decimal color

I want to convert a HEX color (Like #FF0000) to a decimal color (Like 16711680). How do I need to do this?

I've already tried using the Color class, but I can't find a method for converting the colors correctly.

Color hexcolor = Color.decode("#FF0000");
//And then?

Upvotes: 3

Views: 1760

Answers (2)

josejuan
josejuan

Reputation: 9566

One way validating input could be:

public static int parseHex(final String color) {
    final Matcher mx = Pattern.compile("^#([0-9a-z]{6})$", CASE_INSENSITIVE).matcher(color);
    if(!mx.find())
        throw new IllegalArgumentException("invalid color value");
    return Integer.parseInt(mx.group(1), 16);
}

Although not required, you can parse each color component separately:

public static int parseColor(final String color) {
    final Matcher mx = Pattern.compile("^#([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})$", CASE_INSENSITIVE).matcher(color);
    if(!mx.find())
        throw new IllegalArgumentException("invalid color value");
    final int R = Integer.parseInt(mx.group(1), 16);
    final int G = Integer.parseInt(mx.group(2), 16);
    final int B = Integer.parseInt(mx.group(3), 16);
    return (R << 16) + (G << 8) + B;
}

If depend of Color is not a problem, you can use:

public static int parseColor(final String color) {
    final Color c = Color.decode(color);
    return (c.getRed() << 16) + (c.getGreen() << 8) + c.getBlue();
}

On the other way, you can do too:

public static int parseColor(final String color) {
    return 0xFFFFFF & (Color.decode(color).getRGB() >> 8);
}

But since require to know the internal representation, this is not recommended.

Upvotes: 3

stijnb1234
stijnb1234

Reputation: 184

I've already found a anwser because of the comment of vlumi.

https://www.javatpoint.com/java-hex-to-decimal

public static int convertHEXtoDecimal(String HEX) {
    String hex = HEX.replaceAll("#", "");
    String digits = "0123456789ABCDEF";
    hex = hex.toUpperCase();
    int val = 0;
    for (int i = 0; i < hex.length(); i++) {
        char c = hex.charAt(i);
        int d = digits.indexOf(c);
        val = 16 * val + d;
    }
    return val;
}

Upvotes: 1

Related Questions