Hash string into RGB color

后端 未结 5 1819
无人及你
无人及你 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:02

    For any Javascript users out there, I combined the accepted answer from @jeff-foster with the djb2 hash function from erlycoder.

    The result per the question:

    function djb2(str){
      var hash = 5381;
      for (var i = 0; i < str.length; i++) {
        hash = ((hash << 5) + hash) + str.charCodeAt(i); /* hash * 33 + c */
      }
      return hash;
    }
    
    function hashStringToColor(str) {
      var hash = djb2(str);
      var r = (hash & 0xFF0000) >> 16;
      var g = (hash & 0x00FF00) >> 8;
      var b = hash & 0x0000FF;
      return "#" + ("0" + r.toString(16)).substr(-2) + ("0" + g.toString(16)).substr(-2) + ("0" + b.toString(16)).substr(-2);
    }
    

    UPDATE: Fixed the return string to always return a #000000 format hex string based on an edit by @alexc (thanks!).

提交回复
热议问题