ShortGuid--简单便捷高效不区分大小写的短唯一ID

来源:互联网 发布:java开发专业技能 编辑:程序博客网 时间:2024/06/05 05:25

采用base36编码的GUID是一个简单便捷的好办法


    public static class ShortGuid    {        // I choose the base 36 because it generates little bit longer than 62.        // base36 vs. base62 vs. guid        // 25-26 vs. 22-23 vs. 36        private static readonly char[] BASE36 = {                                  '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'                              };        private static string ToBase36String(byte[] toConvert, bool bigEndian = false)        {            if (bigEndian) Array.Reverse(toConvert); // !BitConverter.IsLittleEndian might be an alternative            BigInteger dividend = new BigInteger(toConvert);            var builder = new StringBuilder();            while (dividend != 0)            {                BigInteger remainder;                dividend = BigInteger.DivRem(dividend, 36, out remainder);                builder.Insert(0, BASE36[Math.Abs(((int)remainder))]);            }            return builder.ToString();        }        public static String NewGuid()        {            return ToBase36String(Guid.NewGuid().ToByteArray());        }    }


0 0
原创粉丝点击