.NET Short Unique Identifier

前端 未结 23 1134
忘掉有多难
忘掉有多难 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 11:58

    to not lose characters (+ / -) and if you want to use your guid in an url, it must be transformed into base32

    for 10 000 000 no duplicate key

        public static List guids = new List();
        static void Main(string[] args)
        {
            for (int i = 0; i < 10000000; i++)
            {
                var guid = Guid.NewGuid();
                string encoded = BytesToBase32(guid.ToByteArray());
                guids.Add(encoded);
                Console.Write(".");
            }
            var result = guids.GroupBy(x => x)
                        .Where(group => group.Count() > 1)
                        .Select(group => group.Key);
    
            foreach (var res in result)
                Console.WriteLine($"Duplicate {res}");
    
            Console.WriteLine($"*********** end **************");
            Console.ReadLine();
        }
    
        public static string BytesToBase32(byte[] bytes)
        {
            const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string output = "";
            for (int bitIndex = 0; bitIndex < bytes.Length * 8; bitIndex += 5)
            {
                int dualbyte = bytes[bitIndex / 8] << 8;
                if (bitIndex / 8 + 1 < bytes.Length)
                    dualbyte |= bytes[bitIndex / 8 + 1];
                dualbyte = 0x1f & (dualbyte >> (16 - bitIndex % 8 - 5));
                output += alphabet[dualbyte];
            }
    
            return output;
        }
    

提交回复
热议问题