Base62编码和短网址

短网址一般采用 Base62 编码,Base62 编码是由 10 个数字 26 个大些英文字母和 26 个小写英文字母组成,比如:http://goo.gl/osYa6。这里提供一种对数字进行 Base62 编码的方法。
public static class Base62
{
    
private static string Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    
public static String Encoding(ulong num)
    {
        
if (num < 1)
            
throw new Exception("num must be greater than 0.");

        StringBuilder sb 
= new StringBuilder();
        
for (; num > 0; num /= 62)
        {
            sb.Append(Alphabet[(
int)(num % 62)]);
        }
        
return sb.ToString();
    }

    
public static ulong Decoding(String str)
    {
        str 
= str.Trim();
        
if (str.Length < 1)
            
throw new Exception("str must not be empty.");

        
ulong result = 0;
        
for (int i = 0; i < str.Length; i++)
        {
            result 
+= (ulong)(Alphabet.IndexOf(str[i]) * Math.Pow(62, i));
        }
        
return result;
    }
}
原文地址:https://www.cnblogs.com/anjou/p/2056062.html