Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String to hex color #189

Open
zhudock opened this issue Jun 11, 2018 · 0 comments
Open

String to hex color #189

zhudock opened this issue Jun 11, 2018 · 0 comments

Comments

@zhudock
Copy link
Contributor

zhudock commented Jun 11, 2018

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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant