什么是base62编码,和base64有什么区别?

By - Last updated: 星期三, 五月 27, 2015 Leave a Comment

在网上冲浪的时候,阅读技术文章有时候会看到base62,你可能会问这个base62和base64有什么区别?base62有什么用,难道就是64-62=2的区别?
你还真说对了,与base64编码不同的是去除了两个符号,使得码空间由数字和英文字母组成,一般在短网址应用中会用到,下面列出几个语言的base62实现。

Javascript版

var Base62 = { arr : new Array('v', 'P', 'h', '7', 'z', 'Z', 'w', 'A', '2', 'L', 'y', 'U', '4', 'b', 'G', 'q', '5', 't', 'c', 'V', 'f', 'I', 'M', 'x', 'J', 'i', '6', 'X', 'a', 'S', 'o', 'K', '9', 'C', 'N', 'p', '0', 'O', 'W', 'l', 'j', 'Y', 'T', 'H', 'Q', '8', 'R', 'E', 'n', 'm', 'u', '3', '1', 'B', 'r', 'd', 'g', 'e', 'D', 'k', 'F', 's'), log10 : function(x) { return Math.log(x)/Math.log(10) } , encode : function(str) { var out = ''; for(var t = Math.floor(this.log10(str)/this.log10(62)); t>=0; t--) { var a = Math.floor(str / Math.pow(62, t)); out += this.arr[a]; str = str - (a * Math.pow(62, t)); } return out; }, decode : function(str) { var out = 0; var len = str.length - 1; for(var t = 0; t <= len; t++) { out = out + this.arr.indexOf(str.substr(t,1)) * Math.pow(62, len - t); } return out; } } document.write(Base62.encode(10010));

C#版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; } }

Java版base62

public static StringBuffer encodeBase62(byte[] data) {
	StringBuffer sb = new StringBuffer(data.length * 2);
	int pos = 0, val = 0;
	for (int i = 0; i < data.length; i++) {
		val = (val << 8) | (data[i] & 0xFF);
		pos += 8;
		while (pos > 5) {
			char c = encodes[val >> (pos -= 6)];
			sb.append(
			/**/c == 'i' ? "ia" :
			/**/c == '+' ? "ib" :
			/**/c == '/' ? "ic" : c);
			val &= ((1 << pos) - 1);
		}
	}
	if (pos > 0) {
		char c = encodes[val << (6 - pos)];
		sb.append(
		/**/c == 'i' ? "ia" :
		/**/c == '+' ? "ib" :
		/**/c == '/' ? "ic" : c);
	}
	return sb;
}

public static byte[] decodeBase62(char[] data) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);
	int pos = 0, val = 0;
	for (int i = 0; i < data.length; i++) {
		char c = data[i];
		if (c == 'i') {
			c = data[++i];
			c =
			/**/c == 'a' ? 'i' :
			/**/c == 'b' ? '+' :
			/**/c == 'c' ? '/' : data[--i];
		}
		val = (val << 6) | decodes[c];
		pos += 6;
		while (pos > 7) {
			baos.write(val >> (pos -= 8));
			val &= ((1 << pos) - 1);
		}
	}
	return baos.toByteArray();
}

灵感记录 是本站开发的一款收藏记录创意分享 ,开启高效之门的在线应用。
点击:【收藏】 收藏此文

发表在 代码库 • • ↑Top 文章来源