Last active
September 15, 2022 00:59
-
-
Save fabiolimace/5ac08bcec7242f1ec599a24301f9bd88 to your computer and use it in GitHub Desktop.
Convert ULID to and from UUID in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
# @author: Fabio Lima | |
# @created: 2022-02-10 | |
base16 = '0123456789abcdef' | |
base32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' | |
def encode(number, alphabet): | |
text = '' | |
radix = len(alphabet) | |
while number: | |
text += alphabet[number % radix] | |
number //= radix | |
return text[::-1] or '0' | |
def decode(text, alphabet): | |
number = 0 | |
radix = len(alphabet) | |
for i in text: | |
number = number * radix + alphabet.index(i) | |
return number | |
def to_uuid(ulid): | |
# decode from base-32 | |
number = decode(ulid, base32) | |
# encode the number to base-16 | |
text = encode(number, base16) | |
# add hyphens to the base-16 string to form the canonical string | |
return text[0:8] + '-' + text[8:12] + '-' + text[12:16] + '-' + text[16:20] + '-' + text[20:32] | |
def to_ulid(uuid): | |
# remove hyphens from the canonical | |
# string to form the base-16 string | |
uuid = uuid.replace('-', '') | |
# decode from base-16 | |
number = decode(uuid, base16) | |
# encode the number to base-32 | |
return encode(number, base32) | |
def main(): | |
ulid_in = '5JRB77HQYQ8P08BWPJRF5Q7F06' | |
uuid_in = 'b2c2ce78-dfd7-4580-85f2-d2c3cb73bc06' | |
uuid_out = to_uuid(ulid_in) | |
ulid_out = to_ulid(uuid_in) | |
print('ULID in: ', ulid_in) | |
print('ULID out:', ulid_out) | |
print('UUID in: ', uuid_in) | |
print('UUID out:', uuid_out) | |
if __name__ == '__main__': | |
main() | |
# Notes: | |
# 1. A standard UUID has 6 fixed bits: 4 in the version field and 2 in the variant field. | |
# 2. You must validate the UUID or ULID befor using to_ulid() and to_uuid(). Use REGEX. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output of the script: