将string类型转换成int型:
可以用integer类里面的valueof,但我们这里用parseint
String str="123";
Integer.parseInt(str);
Integer.parseInt(str,2);
其实对于valueof,其实他底层也是用的parseint来进行转换,因此我们来看一下parseint的底层代码看看他是怎么将字符类型转换成数据类型:
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {//最小2进制
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {//最大36进制
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;//判断正负
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
写个方法来将string转换成十进制的数字:(肯定没有底层写的那么完美啦)
private static int toInt(String str,int radix) throws ParseException {
Objects.nonNull(str);
if(str=="")throw new NumberFormatException("str is null");
int firstChar=str.charAt(0);
boolean negative=false;
int i=0;
int len=str.length();
if(firstChar<'0'){
if(firstChar=='-')
negative = true;
else if(firstChar!='+')
throw new NumberFormatException("input number is illegal");
if(len==1)
throw new NumberFormatException("str has illegal character");
i++;
}
int num=0;
while(i<len){
int n=str.charAt(i++);
if(n<'0'||n>'9')
throw new NumberFormatException("middle num illegal");
num=num*radix+(n-48);
}
return negative?-num:num;
}
没有考虑数值类型的范围2-32~231 ,因此超出范围可能还是有问题……
标签:radix,int,NumberFormatException,result,str,字符串,throw From: https://www.cnblogs.com/Liku-java/p/16840922.html