进制解析器,进制解析(string转10进制),同样是copy的大神的代码,以后可能用得上( ̄▽ ̄)"
原网址:https://blog.csdn.net/weixin_34034261/article/details/91585357
public class RadixAnalysis {
private final static char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z' };
private final static Map<Character, Integer> DIGIT_MAP = new HashMap<>();
static {
for (int i = 0; i < DIGITS.length; i++) {
DIGIT_MAP.put(DIGITS[i], i);
}
}
/**
* 支持的最大进制数
*/
private static final int MAX_RADIX = DIGITS.length;
/**
* 支持的最小进制数
*/
private static final int MIN_RADIX = 2;
private static NumberFormatException forInputString(String s) {
return new NumberFormatException("For input string: \"" + s + "\"");
}
/**
* 将字符串转换为长整型数字
*
* @param s
* 数字字符串
* @param radix
* 进制数
*/
public static long toNumber(String s, int radix) {
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < MIN_RADIX) {
throw new NumberFormatException("radix " + radix + " less than Numbers.MIN_RADIX");
}
if (radix > MAX_RADIX) {
throw new NumberFormatException("radix " + radix + " greater than Numbers.MAX_RADIX");
}
long result = 0;
boolean negative = false;
int i = 0, len = s.length();
long limit = -Long.MAX_VALUE;
long multiMin;
Integer digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') {
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (firstChar != '+'){
throw forInputString(s);
}
if (len == 1) {
throw forInputString(s);
}
i++;
}
multiMin = limit / radix;
while (i < len) {
digit = DIGIT_MAP.get(s.charAt(i++));
if (digit == null) {
throw forInputString(s);
}
if (digit < 0) {
throw forInputString(s);
}
if (result < multiMin) {
throw forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw forInputString(s);
}
result -= digit;
}
} else {
throw forInputString(s);
}
return negative ? result : -result;
}
}