Skip to content

Instantly share code, notes, and snippets.

@samuelcatalano-zz
Last active October 18, 2017 12:30
Show Gist options
  • Save samuelcatalano-zz/aadf837520c7e8f69a296a40b882ee4e to your computer and use it in GitHub Desktop.
Save samuelcatalano-zz/aadf837520c7e8f69a296a40b882ee4e to your computer and use it in GitHub Desktop.
package src.main.java;
import java.util.Scanner;
/**
* {@link RGBColors}.
* @author Samuel Catalano
*/
public class RGBColors{
private static final String EMPTY_SPACE = " ";
private static final String RGB888 = "RGB888";
private static final String RGB565 = "RGB565";
/**
* Main method.
* @param args the arguments.
*/
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(true){
String rgbFormat = sc.nextLine();
if(rgbFormat.equals("")){
break;
}
String color = sc.nextLine();
String result = parseColor(rgbFormat, color);
System.out.println(result);
}
}
/**
* Parse color.
* @param rgbFormat the RGB format.
* @param color the color code.
* @return the color parsed.
*/
static String parseColor(String rgbFormat, String color){
String prefix = "0x";
String suffix = "";
String result = "";
if(color.startsWith(prefix) && rgbFormat.equalsIgnoreCase(RGB888)){
Integer r = Integer.valueOf(color.substring(2, 4), 16);
Integer g = Integer.valueOf(color.substring(4, 6), 16);
Integer b = Integer.valueOf(color.substring(6, 8), 16);
result = result.concat(r.toString() + " " + g.toString() + " " + b.toString());
}
else if(color.startsWith(prefix) && rgbFormat.equalsIgnoreCase(RGB565)){
Integer r = Integer.valueOf(color.substring(2, 4), 16);
Integer g = Integer.valueOf(color.substring(4, 6), 16);
Integer b = Integer.valueOf(color.substring(6, 8), 16);
Integer r5 = ((r * 249) + 1014) >> 11;
Integer g6 = ((g * 253) + 505) >> 10;
Integer b5 = ((b * 249) + 1014) >> 11;
result = result.concat(r5.toString() + " " + g6.toString() + " " + b5.toString());
}
else if(! color.startsWith(prefix) && rgbFormat.equalsIgnoreCase(RGB888)){
String[] rgb;
rgb = color.split(EMPTY_SPACE);
Integer r = Integer.valueOf(rgb[0]);
Integer g = Integer.valueOf(rgb[1]);
Integer b = Integer.valueOf(rgb[2]);
suffix = Integer.toHexString(r) + Integer.toHexString(g) + Integer.toHexString(b);
result = (prefix + suffix.toUpperCase());
}
else if(! color.startsWith(prefix) && rgbFormat.equalsIgnoreCase(RGB565)){
String[] rgb;
rgb = color.split(EMPTY_SPACE);
Integer r = Integer.valueOf(rgb[0]);
Integer g = Integer.valueOf(rgb[1]);
Integer b = Integer.valueOf(rgb[2]);
Integer r5 = ((r * 249) + 1014) >> 11;
Integer g6 = ((g * 253) + 505) >> 10;
Integer b5 = ((b * 249) + 1014) >> 11;
suffix = Integer.toHexString(r5) + Integer.toHexString(g6) + Integer.toHexString(b5);
result = (prefix + suffix.toUpperCase());
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment