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)
*/