Java Color to Hex toHexString(Color col)

Here you can find the source of toHexString(Color col)

Description

converts Color to hex String with RGB values

License

Open Source License

Parameter

Parameter Description
Color a parameter

Declaration

final public static String toHexString(Color col) 

Method Source Code


//package com.java2s;
/* //from w ww.j  a  v a  2s . co  m
 GeoGebra - Dynamic Mathematics for Everyone
 http://www.geogebra.org
    
 This file is part of GeoGebra.
    
 This program is free software; you can redistribute it and/or modify it 
 under the terms of the GNU General Public License as published by 
 the Free Software Foundation.
     
 */

import java.awt.Color;

public class Main {
    private static StringBuilder hexSB = null;
    private static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
            'F' };

    /**
     * converts Color to hex String with RGB values
     * @param Color
     * @return
     */
    final public static String toHexString(Color col) {
        byte r = (byte) col.getRed();
        byte g = (byte) col.getGreen();
        byte b = (byte) col.getBlue();

        if (hexSB == null)
            hexSB = new StringBuilder(8);
        else
            hexSB.setLength(0);
        // RED      
        hexSB.append(hexChar[(r & 0xf0) >>> 4]);
        // look up high nibble char             
        hexSB.append(hexChar[r & 0x0f]); // look up low nibble char
        // GREEN
        hexSB.append(hexChar[(g & 0xf0) >>> 4]);
        // look up high nibble char             
        hexSB.append(hexChar[g & 0x0f]); // look up low nibble char
        // BLUE     
        hexSB.append(hexChar[(b & 0xf0) >>> 4]);
        // look up high nibble char             
        hexSB.append(hexChar[b & 0x0f]); // look up low nibble char
        return hexSB.toString();
    }

    final public static String toHexString(char c) {
        int i = c + 0;

        if (hexSB == null)
            hexSB = new StringBuilder(8);
        else
            hexSB.setLength(0);
        hexSB.append("\\u");
        hexSB.append(hexChar[(i & 0xf000) >>> 12]);
        hexSB.append(hexChar[(i & 0x0f00) >> 8]); // look up low nibble char
        hexSB.append(hexChar[(i & 0xf0) >>> 4]);
        hexSB.append(hexChar[i & 0x0f]); // look up low nibble char
        return hexSB.toString();
    }

    final public static String toHexString(String s) {
        StringBuilder sb = new StringBuilder(s.length() * 6);
        for (int i = 0; i < s.length(); i++) {
            sb.append(toHexString(s.charAt(i)));
        }

        return sb.toString();
    }
}

Related

  1. toHexColor(Color col)
  2. toHexColor(final Color color)
  3. toHexColor(final Color color)
  4. toHexString(Color c)
  5. toHexString(Color col)
  6. toHexString(Color color)
  7. toHexString(Color color)
  8. toHexString(Color color)
  9. toHexString(Color color)