ric0chet

RGB to hex converter

Jul 6th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. public class RGBToHexConverter {
  2.  
  3.     // Trying to make this as shitty as possible.
  4.  
  5.     public static String[] hexColors = new String[256 * 256 * 256];
  6.  
  7.     public RGBToHexConverter() {
  8.         generateTable();
  9.     }
  10.  
  11.     public static void generateTable() {
  12.         for(int i = 0; i < hexColors.length; i++) {
  13.             hexColors[i] = String.format("%06x", i);
  14.         }
  15.     }
  16.  
  17.     private int getColorInt(int r, int g, int b) {
  18.         int color = r << 16 | g << 8 | b;
  19.         return color;
  20.     }
  21.  
  22.     private String rgb(int r, int g, int b) {
  23.         // Checking to make sure the colors stay within the bounds
  24.         r = r > -1 && r < 256 ? r : r & 0xff;
  25.         g = g > -1 && g < 256 ? g : g & 0xff;
  26.         b = b > -1 && b < 256 ? b : b & 0xff;
  27.  
  28.         int colorIndex = getColorInt(r, g, b);
  29.         String colorCode = hexColors[colorIndex];
  30.  
  31.         return "#" + colorCode;
  32.     }
  33.  
  34.     public static void main(String[] args) {
  35.         RGBToHexConverter converter = new RGBToHexConverter();
  36.         System.out.println(converter.rgb(47, 91, 105));
  37.     }
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment