YouTube-like GUID

后端 未结 8 1804
灰色年华
灰色年华 2020-12-07 16:17

Is it possible to generate short GUID like in YouTube (N7Et6c9nL9w)?

How can it be done? I want to use it in web app.

相关标签:
8条回答
  • 2020-12-07 16:54

    As mentioned in the accepted answer, it can cause problems if you're using the GUID in the URL. Here is a more complete answer:

        public string ToShortString(Guid guid)
        {
            var base64Guid = Convert.ToBase64String(guid.ToByteArray());
    
            // Replace URL unfriendly characters with better ones
            base64Guid = base64Guid.Replace('+', '-').Replace('/', '_');
    
            // Remove the trailing ==
            return base64Guid.Substring(0, base64Guid.Length - 2);
        }
    
        public Guid FromShortString(string str)
        {
            str = str.Replace('_', '/').Replace('-', '+');
            var byteArray = Convert.FromBase64String(str + "==");
            return new Guid(byteArray);
        }
    

    Usage:

            var guid = Guid.NewGuid();
            var shortStr = ToShortString(guid);
            // shortStr will look something like 2LP8GcHr-EC4D__QTizUWw
            var guid2 = FromShortString(shortStr);
            Assert.AreEqual(guid, guid2);
    
    0 讨论(0)
  • 2020-12-07 16:55

    It might be not the best solution, but you can do something like that:

    string shortUrl = System.Web.Security.Membership.GeneratePassword(11, 0);
    
    0 讨论(0)
  • 2020-12-07 16:57

    It's not a GUID

    Let me jump in with the following

    It uses the TotalMilliseconds from EPOCH and a valid set of characters.

    This will not be globally unique but unique to the instance where it's defines

    public string YoutubeLikeId()
    {
        Thread.Sleep(1);//make everything unique while looping
        long ticks = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1,0,0,0,0))).TotalMilliseconds;//EPOCH
        char[] baseChars = new char[] { '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',
                'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x'};
    
        int i = 32;
        char[] buffer = new char[i];
        int targetBase= baseChars.Length;
    
        do
        {
            buffer[--i] = baseChars[ticks % targetBase];
            ticks = ticks / targetBase;
        }
        while (ticks > 0);
    
        char[] result = new char[32 - i];
        Array.Copy(buffer, i, result, 0, 32 - i);
    
        return new string(result);
    }
    

    The output will come something like

    XOTgBsu
    XOTgBtB
    XOTgBtR
    XOTgBtg
    XOTgBtw
    XOTgBuE
    

    Update: The same can be achieved from Guid as

    var guid = Guid.NewGuid(); 
    guid.ToString("N");
    guid.ToString("N").Substring(0,8);
    guid.ToString("N").Substring(8,4);
    guid.ToString("N").Substring(12,4);
    guid.ToString("N").Substring(16,4);
    guid.ToString("N").Substring(20,12);
    

    For a Guid ecd65132-ab5a-4587-87b8-b875e2fe0f35 it will break it down in chunks as ecd65132 ,ab5a , 4587,87b8,b875e2fe0f35

    but i can't guarantee it to be unique always.

    Update 2: There is also a project called ShortGuid to get a url friendly GUID it can be converted fron/to a regular Guid

    0 讨论(0)
  • 2020-12-07 16:57

    Technically it's not a Guid. Youtube has a simple randomized string generator that you can probably whip up in a few minutes using an array of allowed characters and a random number generator.

    0 讨论(0)
  • 2020-12-07 16:59

    You could use Base64:

    string base64Guid = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
    

    That generates a string like E1HKfn68Pkms5zsZsvKONw==. Since a GUID is always 128 bits, you can omit the == that you know will always be present at the end and that will give you a 22 character string. This isn't as short as YouTube though.

    0 讨论(0)
  • 2020-12-07 17:08

    9 chars is not a GUID. Given that, you could use the hexadecimal representation of an int, which gives you a 8 char string.

    You can use an id you might already have. Also you can use .GetHashCode against different simple types and there you have a different int. You can also xor different fields. And if you are into it, you might even use a Random number - hey, you have well above 2.000.000.000+ possible values if you stick to the positives ;)

    0 讨论(0)
提交回复
热议问题