Skip to content

Instantly share code, notes, and snippets.

@TheKojuEffect
Forked from micahwalter/base58.sql
Last active January 14, 2016 06:07
Show Gist options
  • Save TheKojuEffect/b1d03a8694b3509c8f93 to your computer and use it in GitHub Desktop.
Save TheKojuEffect/b1d03a8694b3509c8f93 to your computer and use it in GitHub Desktop.
base58.sql
CREATE FUNCTION base58_encode(num INT)
RETURNS VARCHAR(255) AS $encoded$
DECLARE
alphabet VARCHAR(255);
base_count INT DEFAULT 0;
encoded VARCHAR(255);
divisor DECIMAL(10, 4);
mod INT DEFAULT 0;
BEGIN
alphabet := '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
base_count := char_length(alphabet);
encoded := '';
WHILE num >= base_count LOOP
divisor := num / base_count;
mod := (num - (base_count * trunc(divisor, 0)));
encoded := concat(substring(alphabet FROM mod + 1 FOR 1), encoded);
num := trunc(divisor, 0);
END LOOP;
encoded = concat(substring(alphabet FROM num + 1 FOR 1), encoded);
RETURN (encoded);
END; $encoded$
LANGUAGE PLPGSQL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment