前些天在做一个新浪微博的应用,在把应用测试的内容发布到新浪微博的时候,发现应用测试的链接地址变成http://t.cn/xxxxxx啦 ,点击链接又跳转到了应用测试地址,于是生了个念头[弄清楚是怎么回事?]。
原来我们发微博的时候有字数的限制,如果发布的微博内容包含网址,而网址会占一定的长度,这就给发布内容的字数上有了限制,我想新浪微博为了更好的用户体验而找出解决这个问题的方法就是把原网址根据算法变短。下面是在网上查到资料[短网址映射算法的理论]:
(1)、将长地址根据MD5生成32位签名串,每段8个字节。
(2)、对这四段循环处理, 取8个字节, 将他看成16进制串与0x3fffffff(30位1)与操作, 即超过30位的忽略处理;
(3)、这30位分成6段, 每5位的数字作为字母表的索引取得特定字符, 依次进行获得6位字符串;
(4)、总的md5串可以获得4个6位串; 取里面的任意一个就可作为这个长url的短url地址;
public static string[] ShortUrl(string url)
{
//可以自定义生成MD5加密字符传前的混合KEY
string key = "Leejor";
//要使用生成URL的字符
string[] chars = new string[]{
"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","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"
};
//对传入网址进行MD5加密
string hex = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key + url, "md5");
string[] resUrl = new string[4];
for (int i = 0; i < 4; i++)
{
//把加密字符按照8位一组16进制与0x3FFFFFFF进行位与运算
int hexint = 0x3FFFFFFF & Convert.ToInt32("0x" + hex.Substring(i * 8, 8), 16);
string outChars = string.Empty;
for (int j = 0; j < 6; j++)
{
//把得到的值与0x0000003D进行位与运算,取得字符数组chars索引
int index = 0x0000003D & hexint;
//把取得的字符相加
outChars += chars[index];
//每次循环按位右移5位
hexint = hexint >> 5;
}
//把字符串存入对应索引的输出数组
resUrl[i] = outChars;
}
return resUrl;
}
使用该方法就会得到四组不同的链接地址 例如:ShortUrl("URL")[0],ShortUrl("URL")[1],ShortUrl("URL")[2],ShortUrl("URL")[3]。
以上算法以及代码均来源于网络资料;
上面还有两个问题比较模糊的是进制转换和位运算[从没用过];