Hash string into RGB color

后端 未结 5 1825
无人及你
无人及你 2021-01-30 08:32

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 doe

5条回答
  •  清歌不尽
    2021-01-30 09:15

    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;
    

提交回复
热议问题