I want to create a short GUID. Is there any way to create a short unique code like short GUID? I want to create a ticket tracking number.
Jeff Atwood has an article on his blog how to shorten a GUID to 20 characters without losing information:
Coding Horror: Equipping our ASCII Armor
Try Base 36, to get unique number all you have to do is use an auto number, and save it as Base36. However in order for them to be random, you will need something else.
What I will do is, hash or encrypt the ticket number as ticket tracking code. Like,
code = Base36(MD5(ticketID+"my secrete"));
If you want tracking code to be unique then I will encrypt with some keys.
The length of GUID is 128bits(16bytes), so if you want to create a short GUID , you have to change GUID's encoding.
For instance, you can use base64 or ASCII85.
/// <summary>
/// Creates a GUID which is guaranteed not to equal the empty GUID
/// </summary>
/// <returns>A 24 character long string</returns>
public static string CreateGuid()
{
Guid guid = Guid.Empty;
while (Guid.Empty == guid)
{
guid = Guid.NewGuid();
}
// Uses base64 encoding the guid.(Or ASCII85 encoded)
// But not recommend using Hex, as it is less efficient.
return Convert.ToBase64String(guid.ToByteArray());
}
unique within one year, visibly 'random'
string UniqueID()
{
var t = DateTime.UtcNow;
long dgit = t.Millisecond * 1000000000L +
t.DayOfYear * 1000000L +
t.Hour * 10000L +
t.Minute * 100L +
t.Second;
return Convert.ToBase64String(BitConverter.GetBytes(dgit).Take(5).ToArray()).TrimEnd('=');
}
here's one with a customizable character set
string UniqueID(string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
{
var t = DateTime.UtcNow;
char[] charArray = CharList.ToCharArray();
var result = new Stack<char>();
var length = charArray.Length;
long dgit = 1000000000000L +
t.Millisecond * 1000000000L +
t.DayOfYear * 1000000L +
t.Hour * 10000L +
t.Minute * 100L +
t.Second;
while (dgit != 0)
{
result.Push(charArray[dgit % length]);
dgit /= length;
}
return new string(result.ToArray());
}
Really depends on your usage.
For example, if you were generating them at a pace less than 1 per second, you could just increment a 32bit int (1/4 the size of a 128bit GUID). That would last you a little over 68 years at the rate of 1 per second.
If you work out your usage, it should be pretty simple to work out the minimum size you can get away with. It will also depend if you want to be able to generate them anywhere, or if they will be generated by a single server or piece of software.