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

系统管理员 2022-07-19 00:08 176阅读 0赞

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

源代码下载地址: http://www.zuidaima.com/share/1828014883720192.htm

方法原型:

  1. public static int parseInt(String s,int radix);
  2. 输入:s表示待转换的字符串;radix表示需要转换成几进制的整数;
  3. 输出:返回一个32位整数。

算法流程图:

  1. ![20140518175152621.jpg][]

JDK中的代码实现:

  1. /**
  2. * 字符串转换成整数
  3. * @param s 待转换字符串
  4. * @param radix 进制
  5. * @return
  6. */
  7. public static int parseInt(String s,int radix){
  8. //边界值处理
  9. if(s==null)
  10. throw new NumberFormatException("null");
  11. if(radix<Character.MIN_RADIX){
  12. throw new NumberFormatException("radix "+radix+" less than Character.MIN_RADIX");
  13. }
  14. if(radix>Character.MAX_RADIX){
  15. throw new NumberFormatException("radix "+radix+" greater than Character.MAX_RADIX");
  16. }
  17. int result=0;
  18. //符号位判断
  19. boolean negative=false;
  20. //字符串偏移指针
  21. int i=0;
  22. int digit;
  23. int max=s.length();
  24. //最大边界值
  25. int limit;
  26. //最大边界值右移一位
  27. int multmin;
  28. if(max>0){
  29. //处理符号
  30. if(s.charAt(0)=='-'){
  31. negative=true;
  32. //边界值为0x80000000
  33. limit=Integer.MIN_VALUE;
  34. i++;
  35. }
  36. else{
  37. //边界值为-0x7fffffff
  38. limit=-Integer.MAX_VALUE;
  39. }
  40. multmin=limit/radix;
  41. if(i<max){
  42. digit=Character.digit(s.charAt(i++), radix);
  43. if(digit<0){
  44. throw NumberFormatException.forInputString(s);
  45. }
  46. else{
  47. result=-digit;
  48. }
  49. }
  50. while(i<max){
  51. //将字符转换成对应进制的整数
  52. digit=Character.digit(s.charAt(i++), radix);
  53. if(digit<0){
  54. throw NumberFormatException.forInputString(s);
  55. }
  56. if(result<multmin){
  57. throw NumberFormatException.forInputString(s);
  58. }
  59. result*=radix;
  60. //result-digit<limit
  61. if(result<limit+digit){
  62. throw NumberFormatException.forInputString(s);
  63. }
  64. result-=digit;
  65. }
  66. }
  67. else{
  68. throw NumberFormatException.forInputString(s);
  69. }
  70. if(negative){
  71. if(i>1){
  72. return result;
  73. }
  74. else{
  75. throw NumberFormatException.forInputString(s);
  76. }
  77. }
  78. else{
  79. return -result;
  80. }
  81. }

关键点:

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

发表评论

表情:
评论列表 (有 0 条评论,176人围观)

还没有评论,来说两句吧...

相关阅读