什么是base62编码,和base有什么区别

发布网友 发布时间:2022-04-22 14:07

我来回答

2个回答

热心网友 时间:2023-08-07 04:36

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

热心网友 时间:2023-08-07 04:37

base编码详解

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com