dyl的gravatar头像
dyl 2014-05-18 18:15:48

JDK源码学习阅读-Integer类中的parseInt方法分析

方法原型:

      public static int parseInt(String s,int radix);

      输入:s表示待转换的字符串;radix表示需要转换成几进制的整数;

      输出:返回一个32位整数。

算法流程图:

      JDK源码学习阅读-Integer类中的parseInt方法分析

JDK中的代码实现:

         /**
	 * 字符串转换成整数
	 * @param s		待转换字符串
	 * @param radix	进制
	 * @return
	 */
	public static int parseInt(String s,int radix){
		//边界值处理
		if(s==null)
			throw new NumberFormatException("null");
		if(radix<Character.MIN_RADIX){
			throw new NumberFormatException("radix "+radix+" less than Character.MIN_RADIX");
		}
		if(radix>Character.MAX_RADIX){
			throw new NumberFormatException("radix "+radix+" greater than Character.MAX_RADIX");
		}
		
		int result=0;
		
		//符号位判断
		boolean negative=false;
		
		//字符串偏移指针
		int i=0;
		
		int digit;
		
		int max=s.length();
		
		//最大边界值
		int limit;
		
		//最大边界值右移一位
		int multmin;
		
		if(max>0){
			//处理符号
			if(s.charAt(0)=='-'){
				negative=true;
				//边界值为0x80000000
				limit=Integer.MIN_VALUE;
				i++;
			}
			else{
				//边界值为-0x7fffffff
				limit=-Integer.MAX_VALUE;
			}
			
			multmin=limit/radix;
			if(i<max){
				digit=Character.digit(s.charAt(i++), radix);
				if(digit<0){
					throw NumberFormatException.forInputString(s);
				}
				else{
					result=-digit;
				}
			}
			while(i<max){
				//将字符转换成对应进制的整数
				digit=Character.digit(s.charAt(i++), radix);
				if(digit<0){
					throw NumberFormatException.forInputString(s);
				}
				
				if(result<multmin){
					throw NumberFormatException.forInputString(s);
				}
				result*=radix;
				//result-digit<limit
				if(result<limit+digit){
					throw NumberFormatException.forInputString(s);
				}
				result-=digit;
			}
		}
		else{
			throw NumberFormatException.forInputString(s);
		}
		if(negative){
			if(i>1){
				return result;
			}
			else{
				throw NumberFormatException.forInputString(s);
			}
		}
		else{
			return -result;
		}
	}

关键点:

  1. 正数的边界值为1至0x7fffffff;负数的边界值为-1至0x80000000;
  2. 代码中将所有数据当做负数(正数)来处理,最后处理符号问题;
  3. 方法中multmin这个变量是为了在循环中result*=radix不会发生越界;


最代码官方编辑于2016-8-6 14:46:02


打赏

最代码最近下载分享源代码列表最近下载
最代码最近浏览分享源代码列表最近浏览
3334004690  LV10 1月15日
long123_356  LV8 2024年5月18日
暂无贡献等级
suiyibawokeyi 2022年6月5日
暂无贡献等级
squarefive  LV2 2020年12月26日
562650727  LV10 2020年9月25日
shuilianbing  LV6 2020年6月8日
moomin709  LV24 2020年2月10日
1157648539 2020年1月2日
暂无贡献等级
luohaipeng  LV23 2019年11月19日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友