大家好,欢迎来到IT知识分享网。
Base62编码
Base62编码与Base64编码类似,都用于数据内容编码。基本原理请参看《Base64算法》。
import java.io.ByteArrayOutputStream; /** * Created by shijiaqi on 16/8/3. */ public class Base62Codec { private static char[] encodes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); private static byte[] decodes = new byte[256]; static { for (int i = 0; i < encodes.length; i++) { decodes[encodes[i]] = (byte) i; } } /** * 将data编码成Base62的字符串 * @param data * @return */ public static String 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.toString(); } /** * 将字符串解码成byte数组 * @param string * @return */ public static byte[] decodeBase62(String string) { if(string==null){ return null; } char[] data=string.toCharArray(); ByteArrayOutputStream baos = new ByteArrayOutputStream(string.toCharArray().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(); } }
以上代码来自网络。
62进制
将数字与62个字符进行转换,可以有效缩减数字长度。不多解释。
直接贴代码:
public class Number62 { public static String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static String encoding(long num) { if(num < 1) throw new IllegalArgumentException("num must be greater than 0."); StringBuilder sb = new StringBuilder(); for (; num > 0; num /= 62) { sb.append(ALPHABET.charAt((int) (num % 62))); } return sb.toString(); } private static long decoding(String str) { if(str==null || str.trim().length() == 0 ){ throw new IllegalArgumentException("str must not be empty."); } long result = 0; for (int i = 0; i < str.length(); i++) { result += ALPHABET.indexOf(str.charAt(i)) * Math.pow(62, i); } return result; } }
类似的代码网上有很多,以上代码来自这里。
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/27674.html