Skip to content

Instantly share code, notes, and snippets.

@cuppster
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuppster/4e50be8807d3dc29d719 to your computer and use it in GitHub Desktop.
Save cuppster/4e50be8807d3dc29d719 to your computer and use it in GitHub Desktop.
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