java基礎之Integer.parseInt(String s ,int radix)方法使用解釋
阿新 • • 發佈:2019-01-10
方法parseInt(String s,int radix)的目的是輸出一個十進位制數,這個數字是“String s”但是我們要知道他是多少進位制的,而方法中“int radix”引數正是來表達這個資訊的。
比如:parseInt(1010,2)
意思就是:輸出2進位制數1010在十進位制下的數.
更直白地說:parseInt(String s,int radix)就是求“int radix”進位制數“String s”的十進位制數是多少。
-----------------------
我們平時用到Integer.parseInt("123");其實預設是呼叫了int i =Integer.parseInt("123",10);
其中10代表的預設是10進位制的,轉換的過程可以看成:
i= 1*10*10+2*10+3
若是
int i = Integer.parseInt("123",16);
即可以看成:
i = 1*16*16+2*16+3 = 291
根據:Character.MIN_RADIX=2和Character.MAX_RADIX=36 則,parseInt(String s, int radix)引數中
radix的範圍是在2~36之間,超出範圍會拋異常。其中s的長度也不能超出7,否則也會拋異常。
比如:parseInt(1010,2)
意思就是:輸出2進位制數1010在十進位制下的數.
更直白地說:parseInt(String s,int radix)就是求“int radix”進位制數“String s”的十進位制數是多少。
-----------------------
我們平時用到Integer.parseInt("123");其實預設是呼叫了int i =Integer.parseInt("123",10);
其中10代表的預設是10進位制的,轉換的過程可以看成:
i= 1*10*10+2*10+3
若是
int i = Integer.parseInt("123",16);
即可以看成:
i = 1*16*16+2*16+3 = 291
根據:Character.MIN_RADIX=2和Character.MAX_RADIX=36 則,parseInt(String s, int radix)引數中
radix的範圍是在2~36之間,超出範圍會拋異常。其中s的長度也不能超出7,否則也會拋異常。
原始碼如下:
- publicstaticint parseInt(String s, int radix)
- throws NumberFormatException
- {
- if (s == null) {
- thrownew NumberFormatException("null");
- }
- if (radix < Character.MIN_RADIX) {
- thrownew NumberFormatException("radix " + radix +
-
" less than Character.MIN_RADIX"
- }
- if (radix > Character.MAX_RADIX) {
- thrownew 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;
- }
- }