Skip to content

Instantly share code, notes, and snippets.

@elifarley
Forked from micahwalter/base58.sql
Last active March 16, 2018 13:57
Show Gist options
  • Save elifarley/56befdc3cffddfc01c03 to your computer and use it in GitHub Desktop.
Save elifarley/56befdc3cffddfc01c03 to your computer and use it in GitHub Desktop.
Order-Preserving Base-58
-- num <= 430804206899405823: <= 10 digits
-- num > 430804206899405823: 11 digits
CREATE FUNCTION opb58enc (@num bigint) RETURNS char(11) WITH SCHEMABINDING AS
BEGIN
DECLARE @alphabet char(58) = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
DECLARE @encoded varchar(11)
DECLARE @divisor bigint
DECLARE @mode int = 0
SET @encoded = ''
WHILE @num >= 58 BEGIN
SET @divisor = @num / 58
SET @mode = @num - 58 * @divisor
SET @encoded = CONCAT(SUBSTRING(@alphabet, @mode + 1, 1), @encoded)
SET @num = @divisor
END
RETURN CONCAT(SUBSTRING(@alphabet, @num + 1, 1), @encoded)
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment