oos-utils icon indicating copy to clipboard operation
oos-utils copied to clipboard

String to hex color

Open zhudock opened this issue 7 years ago • 0 comments

Not sure anybody has any use for this, but I had an odd use case for generating a consistent but unique HEX color code based on input string. I used the Javascript code from DesignedByATurtle as an example

function string_to_hex_color (p_str_i varchar2)
  return varchar2
as
  c_32bit_int_min constant binary_integer := -power(2,32-1); --min 32-bit signed integer
  c_32bit_int_max constant binary_integer := power(2,32-1) - 1; --max 32-bit signed integer
  c_32bit_int_overflow constant number := 4294967296; --max 32-bit number
  c_24bit_rgb constant binary_integer := 16777215; --decimal value of hex FFFFFF

  l_rgb_hex varchar2(6);
  l_hash   number := 0;
begin
  for i in 1 .. length (p_str_i)
  loop
    /* add ascii value of current char
     * bitshift_left l_hash by 5 (can't use oos_util_bit because we need NUMBER not BINARY_INTEGER)
     * subtract l_hash
     * mod result by max 32-bit number
     *
     * if result doesn't fall between min\max 32-bit signed int, add\subtract max 32-bit number
     */
    l_hash := mod(ascii(substr(p_str_i,i,1)) + ((l_hash*power(2,5)) - l_hash), c_32bit_int_overflow);
    l_hash := case when l_hash not between c_32bit_int_min and c_32bit_int_max then sign(l_hash) * (abs(l_hash) - c_32bit_int_overflow) else l_hash end;
  end loop;
  /* bitand final hash value with decimal equivalent of hex FFFFFF
   * lpad to ensure length is never less than 6 char
   */
  l_rgb_hex := oos_util_base.to_hex(oos_util_bit.bitand(l_hash, c_24bit_rgb));
  return upper(lpad(l_rgb_hex, 6, '0'));
end string_to_hex_color;

zhudock avatar Jun 11 '18 15:06 zhudock