Is there a best practice on how to hash an arbitrary string into a RGB color value? Or to be more general: to 3 bytes.
You're asking: When will I ever need this? It doesn't matter to me, but imagine those tube graphs on any GitHub network page. There you can see something like this:
Where every colored line means a distinct git branch. The low tech approach to color these branches would be a CLUT (color lookup table). The more sophisticated version would be:
$branchColor = hashStringToColor(concat($username,$branchname));
Because you want a static color every time you see the branches representation. And for bonus points: How do you ensure an even color distribution of that hash function?
So the answer to my question boils down to the implementation of hashStringToColor()
.
A good hash function will provide a near uniform distribution over the key space. This reduces the question to how do I convert a random 32 bit number to a 3 byte RGB space. I see nothing wrong with just taking the low 3 bytes.
int hash = string.getHashCode();
int r = (hash & 0xFF0000) >> 16;
int g = (hash & 0x00FF00) >> 8;
int b = hash & 0x0000FF;