ruby重写java对URL短地址压缩算法微博短地址原理解析

java实现对URL短地址压缩算法
public class ShortUrl {   
    public static void main(String[] args) {   
        String url = "http://www.sunchis.com";   
        for (String string : ShortText(url)) {   
            print(string);   
        }   
    }   
       
    public static String[] ShortText(String string){   
        String key = "XuLiang";                 //自定义生成MD5加密字符串前的混合KEY   
        String[] 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"   
        };   
           
        String hex = MD5Encode(key + string);   
        int hexLen = hex.length();   
        int subHexLen = hexLen / 8;   
        String[] ShortStr = new String[4];   
           
        for (int i = 0; i < subHexLen; i++) {   
            String outChars = "";   
            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 += chars[index];   
                idx = idx >> 5;   
            }   
            ShortStr[i] = outChars;   
        }   
           
        return ShortStr;   
    }   
       
    private static void print(Object messagr){   
        System.out.println(messagr);   
    }   
}   
测试结果
ShortText("http://www.sunchis.com")[0];  //得到值:Jzyqma   
ShortText("http://www.sunchis.com")[1];  //得到值:QBrMzm   
ShortText("http://www.sunchis.com")[2];  //得到值:bQreM3   
ShortText("http://www.sunchis.com")[3];  //得到值:VNBRna   


ruby实现对URL短地址压缩算法
require 'digest/md5'

def short_text string
	key = "XuLiang"
	chars = [*'a'..'z',*'0'..'9',*'A'..'Z']
	hex = Digest::MD5.hexdigest(key+string)
	hex_len = hex.length
	sub_hex_len = hex_len/8
	short_str = Array.new(4)
	(0...sub_hex_len).each do |i|
		out_chars = ""
   		j = i + 1
   		sub_hex = hex[i * 8...j * 8]
   		idx = 0x3FFFFFFF & sub_hex.to_i(16)
   		(0...6).each do |i|
   			index = 0x0000003D & idx
   			out_chars += chars[index]
   			idx = idx >> 5
   		end
   	short_str[i] = out_chars
	end
	return short_str
end

测试结果
p short_text("http://www.sunchis.com")
["Jzyqma", "QBrMzm", "bQreM3", "VNBRna"]

进行对比相同,完成ruby对短地址的实现,ruby写起来还是要简洁一点的。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值