Skip to content

Instantly share code, notes, and snippets.

@Bloody-Badboy
Created September 14, 2022 05:55
Show Gist options
  • Save Bloody-Badboy/4ac1384abe934bf7120d7d06dae2fefb to your computer and use it in GitHub Desktop.
Save Bloody-Badboy/4ac1384abe934bf7120d7d06dae2fefb to your computer and use it in GitHub Desktop.
Convert color string to argb values #fff -> [255,255,255,255] , #abcdef -> [255,171,205,239]
package dev.arpan;
public class ColorParser {
public static void main(String[] args) {
printColor(parseColorToARGB("#fff"));
printColor(parseColorToARGB("#abc"));
printColor(parseColorToARGB("#000"));
printColor(parseColorToARGB("#ddd"));
printColor(parseColorToARGB("#abcdef"));
printColor(parseColorToARGB("#50dddddd"));
}
public static void printColor(int[] color) {
if (color.length != 4) throw new IllegalArgumentException("Invalid color");
System.out.printf("argb(%d, %d, %d,%d)\n", color[0], color[1], color[2], color[3]);
}
private static int[] parseColorToARGB(String colorString) {
if (colorString.charAt(0) == '#') {
long color = Long.parseLong(colorString.substring(1), 16);
if (colorString.length() == 4) {
color |= (color & 0xF00) << 12 | (color & 0xF00) << 8;
color |= (color & 0x0F0) << 8 | (color & 0x0F0) << 4;
color |= (color & 0x00F) << 4 | (color & 0x00F);
color |= 0xff000000;
} else if (colorString.length() == 7) {
color |= 0xff000000;
} else if (colorString.length() != 9) {
throw new IllegalArgumentException("Invalid color: " + colorString);
}
int a = (int) ((color >> 24) & 0xFF);
int r = (int) ((color >> 16) & 0xFF);
int g = (int) ((color >> 8) & 0xFF);
int b = (int) (color & 0xFF);
return new int[]{a, r, g, b};
}
throw new IllegalArgumentException("Invalid color: " + colorString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment