Skip to content

Instantly share code, notes, and snippets.

@mrisney
Last active August 23, 2017 17:55
Show Gist options
  • Save mrisney/a63cbfd82893b75098758d7204ff09c4 to your computer and use it in GitHub Desktop.
Save mrisney/a63cbfd82893b75098758d7204ff09c4 to your computer and use it in GitHub Desktop.
public class RGBConverter {
public static class RGBCode{
public int red;
public int blue;
public int green;
public RGBCode(int red, int blue, int green){
this.red = red;
this.blue = blue;
this.green = green;
}
}
/**
*
* Decimal -> Hexadecimal
* 0 0
* 1 1
* ...
* 9 9
* 10 A
* 11 B
* 12 C
* 13 D
* 14 E
* 15 F
*/
public static int hexToInt(char a, char b){
int x = a < 65 ? a-48 : a-55;
int y = b < 65 ? b-48 : b-55;
return x*16+y;
}
public static int[] getRGB(String rgb){
int[] ret = new int[3];
for(int i=0; i<3; i++){
ret[i] = hexToInt(rgb.charAt(i*2), rgb.charAt(i*2+1));
}
return ret;
}
public static void main(String[] args) {
// sample input
String input = "#444444";
// remove possible hashmark "#", any other characters.
String hexString = input.replaceAll("[^A-Za-z0-9]", "");
// get a 3 element array of integers
int[] rgbCodes = getRGB(hexString);
// pass in values to constructor
RGBCode rgbCode = new RGBCode(rgbCodes[0],rgbCodes[1],rgbCodes[2]);
System.out.println("red = "+rgbCode.red);
System.out.println("blue = "+rgbCode.blue);
System.out.println("green = "+rgbCode.green);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment