Skip to content
shortuuid

Short UUID code examples

Encoding a UUID as a fixed-length, 22-character Base62, Base58 and Base64url short ID, and decoding it back, with only each language's standard library. They use the same alphabets as the converter, and every example prints the same four lines for 01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17:

034u0i5NnXmfJTzCqD24Pv
1CgqRXNt3k857DzMnp4uk2
AaG7B5oAfD2fGmstTowKFw
01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17

Short UUIDs in JavaScript

BigInt keeps all 128 bits exact; a Number would silently round them. Buffer is Node.js; in a browser, build the Base64url string with btoa and replace + / with - _.

const B62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

function encode(uuid, alphabet) {
  let n = BigInt("0x" + uuid.replace(/-/g, ""));
  const base = BigInt(alphabet.length);
  let s = "";
  while (n > 0n) {
    s = alphabet[Number(n % base)] + s;
    n /= base;
  }
  return s.padStart(22, alphabet[0]); // fixed length, so short IDs sort like the UUIDs
}

function decode(short, alphabet) {
  let n = 0n;
  for (const ch of short) {
    const d = alphabet.indexOf(ch);
    if (d < 0) throw new Error(`not in the alphabet: ${ch}`);
    n = n * BigInt(alphabet.length) + BigInt(d);
  }
  if (n >> 128n) throw new Error("more than 128 bits: not a UUID");
  return hyphenate(n.toString(16).padStart(32, "0"));
}

const hyphenate = (h) => `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;

// Base64url encodes the 16 bytes (RFC 4648), not the number, so it needs no BigInt.
const toBase64url = (uuid) => Buffer.from(uuid.replace(/-/g, ""), "hex").toString("base64url");
const fromBase64url = (s) => hyphenate(Buffer.from(s, "base64url").toString("hex"));

const id = "01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17";
console.log(encode(id, B62));
console.log(encode(id, B58));
console.log(toBase64url(id));
console.log(decode(encode(id, B62), B62));
if (fromBase64url(toBase64url(id)) !== id) throw new Error("Base64url round trip failed");

Short UUIDs in Python

Python's integers have no size limit, and uuid.UUID(int=...) rejects anything over 128 bits. urlsafe_b64decode insists on = padding, so put it back first.

import base64
import uuid

B62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"


def encode(u: uuid.UUID, alphabet: str) -> str:
    n, s = u.int, ""
    while n:
        n, r = divmod(n, len(alphabet))
        s = alphabet[r] + s
    return s.rjust(22, alphabet[0])  # fixed length, so short IDs sort like the UUIDs


def decode(short: str, alphabet: str) -> uuid.UUID:
    n = 0
    for ch in short:
        n = n * len(alphabet) + alphabet.index(ch)  # ValueError if ch isn't in the alphabet
    return uuid.UUID(int=n)  # ValueError if it's more than 128 bits


def to_base64url(u: uuid.UUID) -> str:
    return base64.urlsafe_b64encode(u.bytes).rstrip(b"=").decode()


def from_base64url(s: str) -> uuid.UUID:
    return uuid.UUID(bytes=base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)))


u = uuid.UUID("01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17")
print(encode(u, B62))
print(encode(u, B58))
print(to_base64url(u))
print(decode(encode(u, B62), B62))
assert from_base64url(to_base64url(u)) == u

Short UUIDs in Go

Only the standard library: math/big for the base conversion, encoding/base64's RawURLEncoding for Base64url without padding.

package main

import (
	"encoding/base64"
	"encoding/hex"
	"errors"
	"fmt"
	"math/big"
	"strings"
)

const B62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

func parseUUID(s string) ([16]byte, error) {
	var u [16]byte
	b, err := hex.DecodeString(strings.ReplaceAll(s, "-", ""))
	if err != nil || len(b) != 16 {
		return u, errors.New("not a UUID")
	}
	copy(u[:], b)
	return u, nil
}

func formatUUID(u [16]byte) string {
	return fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:])
}

func encode(u [16]byte, alphabet string) string {
	n := new(big.Int).SetBytes(u[:])
	base, mod := big.NewInt(int64(len(alphabet))), new(big.Int)
	out := make([]byte, 22)
	for i := 21; i >= 0; i-- { // fixed length: the leading digits are the alphabet's zero
		n.DivMod(n, base, mod)
		out[i] = alphabet[mod.Int64()]
	}
	return string(out)
}

func decode(s, alphabet string) ([16]byte, error) {
	var u [16]byte
	n, base := new(big.Int), big.NewInt(int64(len(alphabet)))
	for _, c := range s {
		d := strings.IndexRune(alphabet, c)
		if d < 0 {
			return u, fmt.Errorf("not in the alphabet: %q", c)
		}
		n.Mul(n, base).Add(n, big.NewInt(int64(d)))
	}
	if n.BitLen() > 128 {
		return u, errors.New("more than 128 bits: not a UUID")
	}
	n.FillBytes(u[:])
	return u, nil
}

func main() {
	u, _ := parseUUID("01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17")
	fmt.Println(encode(u, B62))
	fmt.Println(encode(u, B58))
	fmt.Println(base64.RawURLEncoding.EncodeToString(u[:]))
	back, err := decode(encode(u, B62), B62)
	if err != nil {
		panic(err)
	}
	fmt.Println(formatUUID(back))
}

Short UUIDs in Java

BigInteger does the base conversion; the decoded number splits back into the two longs java.util.UUID is made of.

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.UUID;

public class ShortUuid {
    static final String B62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    static final String B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

    static byte[] bytes(UUID u) {
        return ByteBuffer.allocate(16).putLong(u.getMostSignificantBits()).putLong(u.getLeastSignificantBits()).array();
    }

    static String encode(UUID u, String alphabet) {
        BigInteger n = new BigInteger(1, bytes(u)), base = BigInteger.valueOf(alphabet.length());
        StringBuilder sb = new StringBuilder();
        while (sb.length() < 22) { // fixed length: the leading digits are the alphabet's zero
            BigInteger[] qr = n.divideAndRemainder(base);
            sb.append(alphabet.charAt(qr[1].intValue()));
            n = qr[0];
        }
        return sb.reverse().toString();
    }

    static UUID decode(String s, String alphabet) {
        BigInteger n = BigInteger.ZERO, base = BigInteger.valueOf(alphabet.length());
        for (char c : s.toCharArray()) {
            int d = alphabet.indexOf(c);
            if (d < 0) throw new IllegalArgumentException("not in the alphabet: " + c);
            n = n.multiply(base).add(BigInteger.valueOf(d));
        }
        if (n.bitLength() > 128) throw new IllegalArgumentException("more than 128 bits: not a UUID");
        return new UUID(n.shiftRight(64).longValue(), n.longValue());
    }

    public static void main(String[] args) {
        UUID u = UUID.fromString("01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17");
        System.out.println(encode(u, B62));
        System.out.println(encode(u, B58));
        System.out.println(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes(u)));
        System.out.println(decode(encode(u, B62), B62));
    }
}