Is there any way to create a short unique code like short GUID?
Asked Answered
H

6

28

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.

Hyacinthia answered 14/11, 2011 at 6:56 Comment(12)
The shorter it is, the less unique it is (noting that Guid is not truly "unique"). How short? and could it come from, say, a database identity key?Oliguria
Is there a reason a GUID wont work?Mardis
How about just using parts of a guid?Unbelt
How short? Short as in Int16?Strasser
@Lasse Parts of Guids aren't guaranteed to be unique.Strasser
@MichaelStum neither are guids, if you get enough of them ;p Here's two I thought of earlier... "00000...012" and "00000...012" - dang it!Oliguria
Do you need it globally unique? (Meaning: To be generated on lots of machines? An unique across lots of machines?)Chalkstone
@Marc: you have more chance of winning the lottery 1000 times in a row than generating 2 equal GUIDs! ;)Paquin
I know that, but neither are guids.Unbelt
@Mitch exactly! there is a chance! the point I was trying to make is that the size is related to uniqueness, and that technically - technically even with a large number you aren't absolutely guaranteed unique. Understanding the context of the question is therefore key, hence the prompts here for more info.Oliguria
I don't need to it be globally uniqueHyacinthia
If you don't need more than 63 bits worth of keys you can get the same results with a long github.com/joshclark/Flakey (you could still encode this if you want a better human spoken value)Emogene
M
19

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());
    }
Motch answered 14/11, 2011 at 8:6 Comment(0)
A
16

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

Adamsun answered 14/11, 2011 at 7:2 Comment(2)
Really good resource, but it would be helpful if you included enough information from the article to make a 20 character guid in case this article is ever removed from the internet.Iand
Which has apparently happened. Time to re-invent the wheel...Battle
T
5

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());
}
Tetchy answered 2/12, 2014 at 0:28 Comment(1)
Be aware that when using this method in a loop for example, it would generate the same ID over and over again untill a millisecond has passed.Calie
D
4

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.

Danicadanice answered 14/11, 2011 at 7:3 Comment(0)
D
4

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.

Dukie answered 14/11, 2011 at 7:17 Comment(0)
U
1

There is also am alternative library to convert Guid to a shorter 26-char text representation. Instead of Base64 encoding it uses Base32 dictionary, which is URL-safe and case-insensitive.

var guid = Guid.NewGuid();  // b392ebf5-88d3-49b9-9ad8-1d4a73431787
var shorterGuid = guid.ToShorterString(); // yrpt5gynl2wonaqs3p5baksrkw

NuGet link: https://www.nuget.org/packages/SourceExpress.ShorterGuid/

GitHub link: https://github.com/SourceExpress/shorter-guid

Unexampled answered 6/11, 2022 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.