【转】一个短URL生成算法

本文深入分析了为什么大多数程序员难以成为架构师的原因,并提供了有效的成长路径和建议,旨在帮助开发者突破职业发展瓶颈,实现从码农到架构师的转变。
import java.security.MessageDigest;

public class UrlUtils {

	private final static String[] HEX_DIGITS = { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	private final static String[] SURL_CHARS = new String[] { // 要使用生成URL的字符
		"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" };
	
	static String byteArrayToHexString(byte[] b) {
		StringBuilder resultSb = new StringBuilder();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		
		return resultSb.toString();
	}

	static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		
		return HEX_DIGITS[d1] + HEX_DIGITS[d2];
	}

	static String md5Encode(String origin) {
		String resultStr = null;
		try {
			resultStr = new String(origin).trim();
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultStr = byteArrayToHexString(md.digest(resultStr.getBytes("UTF-8")));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return resultStr;
	}

	/**
	 * @param key 自定义生成MD5加密字符串前的混合KEY
	 * @param url 需要转换短URL的地址
	 * @return 为url生成四个短URL字符
	 */
	public static String[] shortUrl(String key, String url) {
		if(key == null || url == null)
		{
			throw new IllegalArgumentException("shortUrl(String key, String url) need param `key` and `url`!");
		}
		
		String hex = md5Encode(key + url);
		int hexLen = hex.length();
		int subHexLen = hexLen / 8;
		
		String[] shortUrls = new String[4];
		StringBuilder outChars = new StringBuilder();
		
		for (int i = 0; i < subHexLen; i++) {
			outChars.delete(0, outChars.length());
			int j = i + 1;
			String subHex = hex.substring(i * 8, j * 8);
			long idx = Long.valueOf("3FFFFFFF", 16) & Long.valueOf(subHex, 16);

			for (int k = 0; k < 6; k++) {
				int index = (int) (Long.valueOf("0000003D", 16) & idx);
				outChars.append(SURL_CHARS[index]);
				idx = idx >> 5;
			}
			
			shortUrls[i] = outChars.toString();
		}

		return shortUrls;
	}

	public static void main(String[] args) {
	    String url = "http://www.oschina.net/question/59519_82623";   
            for (String string : shortUrl("test_key", url)) {   
               System.out.println(string); 
            }
            
            // maEJju
            // AjmIja
            // NNjQJz
            // uaUnYv
	}

}





转载于:https://my.oschina.net/jsan/blog/534905

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值