Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Last active Jan 18, 2021
Embed
What would you like to do?
Convert UUIDs to/from base58
module Uu58
# Convert a string UUID to a base58 string representation.
#
# Output will be padded up to 22 digits if necessary.
#
# Behaviour is undefined if passing something other than a 128-bit
# hex string in network order with optional interstitial hyphens.
def self.uuid_to_base58(uuid, alphabet = SecureRandom::BASE58_ALPHABET)
ary = uuid.delete("-").to_i(16).digits(58).reverse
ary.unshift(0) while ary.length < 22
alphabet.values_at(*ary).join
end
# Convert a base58 number to a UUID.
#
# Input should be a big-endian base58 string representation of
# a whole number less than 2^128.
def self.base58_to_uuid(base58_val, alphabet = SecureRandom::BASE58_ALPHABET)
num = base58_val.chars.reverse_each.with_index.inject(0) do |acc, (digit, position)|
digit_integer_value = alphabet.index(digit)
raise ArgumentError, 'invalid base58 string' if digit_integer_value.nil?
acc + digit_integer_value * 58**position
end
"%08x-%04x-%04x-%04x-%04x%08x" % [
(num >> 96) & 0xFFFFFFFF,
(num >> 80) & 0xFFFF,
(num >> 64) & 0xFFFF,
(num >> 48) & 0xFFFF,
(num >> 32) & 0xFFFF,
num & 0xFFFFFFFF
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment