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()));
}
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));
}
I ran into this question while looking for a Ruby solution, so I thought I would add an answer for Ruby in case someone follows the same path I did. I ended up using the following method, which creates the same six digit hex code from a string by using String.hash
and the optional base-specifying parameter of Fixnum.to_s
. It slices from 1
rather than 0
to skip negative signs.
def color_from_string(query)
'#'+query.hash.to_s(16).slice(1,6)
end
How about and
ing the hashcode
with 0x00FFFFFF
(or 0xFFFFFF
if you want to default the alpha channel)? For example:
private String getColorCode(String inputString)
{
String colorCode = String.format("#%06x", 0xFFFFFF & inputString.hashCode());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With