Skip to content
Advertisement

Compute hex color code for an arbitrary string

Heading

Is there a way to map an arbitrary string to a HEX COLOR code. I tried to compute the HEX number for string using string hashcode. Now I need to convert this hex number to six digits which are in HEX color code range. Any suggestions ?

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + Integer.toHexString(programs[i].hashCode()));
}

Advertisement

Answer

If you don’t really care about the “meaning” of the color you can just split up the bits of the int (remove the first for just RGB instead of ARGB)

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + intToARGB(programs[i].hashCode()));
}
....
public static String intToARGB(int i){
    return Integer.toHexString(((i>>24)&0xFF))+
        Integer.toHexString(((i>>16)&0xFF))+
        Integer.toHexString(((i>>8)&0xFF))+
        Integer.toHexString((i&0xFF));
}

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement