先來說明一下Integer.parseInt(String s, int radix)的功能。
Integer.parseInt(String s, int radix)就是將整數字符串s(radix用來指明s是幾進制)轉換成10進制的整數,顯然前提是s爲整數字符串。比如 s可以爲“1314520”、“5201314”等。不可以爲“我愛你一生一世”或者“I love you forever”等之類的非整數字符串。
那麼,Integer.pareseInt("10086",10)就是將10進制整數字符串“10086”轉換成10進制的整數10086。(有些說法是爲了便於表達)
下面我們來了解一下它的具體的內部機制。
jdk中 java.lang.Integer中的源碼如下:
1、
- public static int parseInt(String s) throws NumberFormatException
- {
- return parseInt(s,10);
- }
2、
- public static int parseInt(String s, int radix)throws NumberFormatException
- {
- if (s == null) {
- throw new NumberFormatException("null");
- }
- if (radix < Character.MIN_RADIX) { //Character.MIN_RADIX=2
- throw new NumberFormatException("radix " + radix +
- " less than Character.MIN_RADIX");
- }
- if (radix > Character.MAX_RADIX) { //Character.MAN_RADIX=36
- throw new NumberFormatException("radix " + radix +
- " greater than Character.MAX_RADIX");
- }
- int result = 0;
- boolean negative = false;
- int i = 0, max = s.length();
- int limit;
- int multmin;
- int digit;
- if (max > 0) {
- if (s.charAt(0) == '-') {
- negative = true;
- limit = Integer.MIN_VALUE;
- i++;
- } else {
- 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) {
- // 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);
- }
- if (negative) {
- if (i > 1) {
- return result;
- } else { /* Only got "-" */
- throw NumberFormatException.forInputString(s);
- }
- } else {
- return -result;
- }
- }
我們以Integer.parseInt("110",10)爲例。內部的轉換過程其實是這樣的:
i= 1*10*10+1*10+0*1;
若是 Integer.parseInt("111",2)呢?
顯然麼 i = 1*2*2+1*2+1*1。爲了便於理解,直接這樣稱呼它們吧: 10進制整數字符串“110”,2進制整數字符串“111”。這時候,還有個問題,就是可以寫成Integer.parseInt(“119”, 2)嗎?顯然是不對滴!2進制數怎麼可能出現9呢。如果這樣寫,系統會拋出java.lang.NumberFormatException異常。
細心的朋友會注意到,在函數內部有這樣的約束條件:Character.MAX_RADIX
>= radix >= Character.MIN_RADIX 。
根據:Character.MIN_RADIX=2和Character.MAX_RADIX=36 則,parseInt(String s, int radix)參數中
radix的範圍是在2~36之間,超出範圍會拋異常。其中s的長度也不能超出7,否則也會拋異常。
根據:Character.MIN_RADIX=2和Character.MAX_RADIX=36 則,parseInt(String s, int radix)參數中
radix的範圍是在2~36之間,超出範圍會拋異常。其中s的長度也不能超出7,否則也會拋異常。