Convert three int values into a hex string - Java java.lang

Java examples for java.lang:Hex

Description

Convert three int values into a hex string

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int r = 2;
        int g = 2;
        int b = 2;
        boolean inverseOrder = true;
        System.out.println(getHexColor(r, g, b, inverseOrder));
    }/*from  w w w .ja  v  a2  s .  co  m*/

    /**
     * Convert three int values into a hex string
     * 
     * @param r red
     * @param g green
     * @param b blue
     * @param inserverOrder set true to use inverse order of RGB => BGR
     * @return RGB string in hex format
     */
    public static String getHexColor(int r, int g, int b,
            boolean inverseOrder) {
        String red, green, blue;
        String val = Integer.toHexString(r).toUpperCase();
        red = val.length() == 1 ? "0" + val : val; // add leading zero
        val = Integer.toHexString(g).toUpperCase();
        green = val.length() == 1 ? "0" + val : val; // add leading zero
        val = Integer.toHexString(b).toUpperCase();
        blue = val.length() == 1 ? "0" + val : val; // add leading zero
        if (!inverseOrder) {
            return blue + green + red;
        } else {
            return red + green + blue;
        }
    }
}

Related Tutorials