Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Create short GUIDs with a custom alphabet
using System;
using System.Numerics;
namespace Cuppster
{
/// <summary>
/// converted from the python version at https://github.com/stochastic-technologies/shortuuid
/// </summary>
class ShortUUID
{
private char[] _alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".ToCharArray();
private int _alphaLen;
public ShortUUID()
{
_alphaLen = _alphabet.Length;
}
public ShortUUID(char[] alphabet)
{
_alphabet = alphabet;
_alphaLen = _alphabet.Length;
}
public string Uuid()
{
var uuid = Guid.NewGuid();
return Encode(uuid);
}
private string Encode(Guid uuid)
{
var uuidBytes = uuid.ToByteArray();
// ensure that the most-significant bit of the last byte (because it's little endian) is zero
// see: http://stackoverflow.com/questions/6141745/shift-a-128-bit-signed-biginteger-to-always-be-positive
byte[] padded = new byte[uuidBytes.Length + 1];
uuidBytes.CopyTo(padded, 0);
padded[uuidBytes.Length] = 0;
BigInteger big = new BigInteger(padded);
return NumToString(big);
}
private string NumToString(BigInteger number)
{
var output = string.Empty;
var len = new BigInteger(_alphaLen);
BigInteger digit;
while (0 < number)
{
number = BigInteger.DivRem(number, len, out digit);
output += _alphabet[(int)digit];
}
return output;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment