.NET Short Unique Identifier

前端 未结 23 1108
忘掉有多难
忘掉有多难 2020-12-07 11:27

I need a unique identifier in .NET (cannot use GUID as it is too long for this case).

Do people think that the algorithm used here is a good candidate or do you have

23条回答
  •  [愿得一人]
    2020-12-07 12:18

    22 chars, url safe, and retains Guid uniqueness.

    // Our url safe, base 64 alphabet:
    const string alphabet = "-_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    // Sanitized Guid string. Preserve the last two hex chars
    var guidStr = "929F7C4D4B2644E1A122A379C02D6345";
    var lastTwo = guidStr.Substring(30, 2);
    
    string shortGuid = "";
    
    // Iterate over the ten groups of 3 hex chars: 929 F7C 4D4 B26 44E 1A1 22A 379 C02 D63
    for (var i = 0; i < 10; i++)
    {
        var hex = guidStr.Substring(i*3, 3);              // Get the next 3 hex chars
        var x = Convert.ToInt32(hex, 16);                 // Convert to int
        shortGuid += $"{alphabet[x/64]}{alphabet[x%64]}"; // Lookup the two-digit base64 value
    }
    shortGuid += lastTwo; // Don't forget the last two
    
    Console.WriteLine(shortGuid);
    

    Output:

    yDXWhiGAfc4v6EbTK0Px45
    

提交回复
热议问题