package com.g4m; import java.util.Stack; public class JingzhiTest { private final static String _str="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; private static char[] charSet = _str.toCharArray(); private static int len = _str.length(); private static int checkNum = 10; /** * 将10进制转化为62进制 * @param number * @return */ public static String numTo62String(long number){ Long rest=number; Stack<Character> stack=new Stack<Character>(); StringBuilder result=new StringBuilder(0); while(rest!=0){ stack.add(charSet[new Long((rest-(rest/62)*62)).intValue()]); rest=rest/62; } for(;!stack.isEmpty();){ result.append(stack.pop()); } return result.toString(); } /** * 生成长度为length的字符串,length > 1 * @param length * @return */ public static String createRandom(int length) { if(length < 2) { return ""; } StringBuffer str = new StringBuffer(); for (int i = 0; i < length-1; i++) { int a = (int) (Math.random()*62); //0-1,等于0,不等于1 str.append(charSet[a]); } return str.toString() + getCheckCode(str.toString()); } /** * 生成长度为length的字符串,length > 1 * @param length * @return */ public static String createStringById(long id,int length) { String strNum = numTo62String(id); StringBuffer str = new StringBuffer(); for (int i = strNum.length(); i < length-1; i++) { str.append(0); } return getCheckCode(str.toString()+strNum)+str.toString()+strNum; } /** * 生成长度为length的字符串,length > 1 * @param length * @return */ public static String createStringById(long id) { return createStringById(id,6); } /** * 添加校验位 * @param string * @return */ private static char getCheckCode(String string) { long unm = toNum(string)+checkNum; int a = (int) (unm%62); return charSet[a]; } /** * 字符串转数字 * @param s * @return */ public static long toNum(String s) { int a = s.length()-1; long val=0; for(int i=a;i>=0;i--){ char c = s.charAt(i); val += (_str.indexOf(c)*Math.pow(len, a-i)); } return val; } /** * 校验短链是否正确 * @param link * @return */ public static boolean checkShortLink(String link) { if(link==null) { return false; } if(link.length()<2) { return true; } String substring = link.substring(1, link.length()); char charAt = link.charAt(0); char checkCode = getCheckCode(substring); if((int)charAt == (int)(checkCode)) { return true; } return false; } /** * @param args */ public static void main(String[] args) { String createStringById = createStringById(1l); System.out.println("id:"+createStringById); boolean checkShortLink = checkShortLink(createStringById); System.out.println("check:"+checkShortLink); //生成随机字符串 String createRandom = createRandom(6); System.out.println(createRandom); //校验随机字符串 boolean checkShortLink1 = checkShortLink("YB0mEmm"); System.out.println(checkShortLink1); } }