YouTube-like GUID

后端 未结 8 1846
灰色年华
灰色年华 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: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

提交回复
热议问题