Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to convert from HEX color to RGB in Java

2 Answers

0 votes
public class HexToRGB {
    public static int[] hexToRgb(String hex) {
        // Remove the hash at the beginning if it's there
        hex = hex.replace("#", "");

        // Parse the hex string into an integer
        int intValue = Integer.parseInt(hex, 16);

        // Extract the red, green, and blue components
        int r = (intValue >> 16) & 0xFF;
        int g = (intValue >> 8) & 0xFF;
        int b = intValue & 0xFF;

        return new int[]{r, g, b};
    }

    public static void main(String[] args) {
        String hexColor = "#4CFF05";
        
        int[] rgb = hexToRgb(hexColor);
        
        System.out.println("RGB: (" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")");
    }
}


 
/*
run:

RGB: (76, 255, 5)
     
*/

 



answered Mar 6, 2025 by avibootz
0 votes
public class HexToRGB {
    public static int[] hexToRgb(String hex) {
        // Remove the hash at the beginning if it's there
        hex = hex.replace("#", "");

        // Expand 3-digit shorthand hex codes
        if (hex.length() == 3) {
            StringBuilder expandedHex = new StringBuilder();
            for (char ch : hex.toCharArray()) {
                expandedHex.append(ch).append(ch);
            }
            hex = expandedHex.toString();
        }

        // Parse the hex string into an integer
        int intValue = Integer.parseInt(hex, 16);

        // Extract the red, green, and blue components
        int r = (intValue >> 16) & 0xFF;
        int g = (intValue >> 8) & 0xFF;
        int b = intValue & 0xFF;

        return new int[]{r, g, b};
    }

    public static void main(String[] args) {
        String hexColor1 = "#4CFF05";
        int[] rgb1 = hexToRgb(hexColor1);
        System.out.println("RGB: (" + rgb1[0] + ", " + rgb1[1] + ", " + rgb1[2] + ")");

        String hexColor2 = "#f00";
        int[] rgb2 = hexToRgb(hexColor2);
        System.out.println("RGB: (" + rgb2[0] + ", " + rgb2[1] + ", " + rgb2[2] + ")");
    }
}

 
/*
run:

RGB: (76, 255, 5)
RGB: (255, 0, 0)
     
*/

 



answered Mar 7, 2025 by avibootz

Related questions

1 answer 103 views
2 answers 97 views
2 answers 71 views
2 answers 78 views
2 answers 84 views
1 answer 59 views
...