ShortGuid--大文字と小文字を区別せずに簡単で効率的な短い一意のID
1675 ワード
ベース36コードのGUIDを採用するのは簡単で便利な良い方法です
public static class ShortGuid
{
// I choose the base 36 because it generates little bit longer than 62.
// base36 vs. base62 vs. guid
// 25-26 vs. 22-23 vs. 36
private static readonly char[] BASE36 = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};
private static string ToBase36String(byte[] toConvert, bool bigEndian = false)
{
if (bigEndian) Array.Reverse(toConvert); // !BitConverter.IsLittleEndian might be an alternative
BigInteger dividend = new BigInteger(toConvert);
var builder = new StringBuilder();
while (dividend != 0)
{
BigInteger remainder;
dividend = BigInteger.DivRem(dividend, 36, out remainder);
builder.Insert(0, BASE36[Math.Abs(((int)remainder))]);
}
return builder.ToString();
}
public static String NewGuid()
{
return ToBase36String(Guid.NewGuid().ToByteArray());
}
}