微博mid和id转换
mid为62进制编码,id为常见的10进制编码。
id从低位到高位,7个数字为一组,转换为62进制,并顺序合并,即转换为mid。
mid从地位到高位,4个字母为一组,转换为10进制,并右移7位,计算和,得到id。
7位的10进制数最大为9999999,转换为62进制后为FXsj;8位的10进制数最大为99999999,转换为62进制后为9FXsj。
7位分隔10进制数,能保证最多获得4位62进制数。
参考了http://blog.csdn.net/dier4836/article/details/7827908,但是他的mid计算id有问题。
package com.founder.weibocrawler.util; public class WeiboIDUtils { public static void main(String[] args) { System.out.println(Mid2Id("D5DVt7A9n")); System.out.println(Id2Mid("3913451191807261")); } public static String Mid2Id(String mid) { long id = 0L; // 从最后往前以4字节为一组读取字符 int count = 0; for (int i = mid.length() - 4; i > -4; i = i - 4) { int offset = i < 0 ? 0 : i; int len = i < 0 ? mid.length() % 4 : 4; String str = Encode62ToLong(mid.substring(offset, offset + len)).toString(); // 不足7位补0 if (offset != 0) str = String.format("%07d", Long.valueOf(str)); id = (long) (Long.valueOf(str) * Math.pow(10, 7 * count) + id); count++; } return id + ""; } public static String Id2Mid(String id) { String mid = ""; for (int i = id.length() - 7; i > -7; i = i - 7) { int offset = i < 0 ? 0 : i; int len = i < 0 ? id.length() % 7 : 7; String str = LongToEnode62(Long.valueOf(id.substring(offset, offset + len))); mid = str + mid; } return mid; } private static String str62keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static Long Encode62ToLong(String str62) { long long10 = 0; for (int i = 0; i < str62.length(); i++) { double n = str62.length() - i - 1; long10 += Long.valueOf(str62keys.indexOf(str62.substring(i, i + 1)) * (long) Math.pow(62, n) + ""); } return long10; } public static String LongToEnode62(long long10) { String str62 = ""; int offset = 0; while (long10 != 0) { offset = Integer.valueOf(long10 % 62 + ""); str62 = str62keys.substring(offset, offset + 1) + str62; long10 = (long) Math.floor(long10 / 62.0); } return str62; } }