Method Prototypes:
public static int parseint (String s,int radix);
Input: s represents the string to be converted; Radix represents the integer that needs to be converted into a binary number;
Output: Returns a 32-bit integer.
Algorithm Flowchart:
Code implementations in the JDK:
1 /**2 * String converted to integer3 * @params to convert the string4 * @paramRadix in the system5 * @return6 */7 Public Static intparseint (String S,intRadix) {8 //Boundary Value Processing9 if(s==NULL)Ten Throw NewNumberFormatException ("null"); One if(radix<Character.min_radix) { A Throw NewNumberFormatException ("Radix" +radix+ "less than Character.min_radix"); - } - if(radix>Character.max_radix) { the Throw NewNumberFormatException ("Radix" +radix+ "greater than Character.max_radix"); - } - - intResult=0; + - //symbol bit judgment + BooleanNegative=false; A at //string offset pointer - intI=0; - - intDigit; - - intmax=s.length (); in - //Maximum boundary value to intlimit; + - //maximum boundary value shift right one the intmultmin; * $ if(max>0){Panax Notoginseng //Working with symbols - if(S.charat (0) = = '-'){ theNegative=true; + //boundary value is 0x80000000 Alimit=Integer.min_value; thei++; + } - Else{ $ //boundary value is -0x7fffffff $limit=-Integer.max_value; - } - themultmin=limit/Radix; - if(i<max) {WuyiDigit=character.digit (S.charat (i++), radix); the if(digit<0){ - Thrownumberformatexception.forinputstring (s); Wu } - Else{ Aboutresult=-Digit; $ } - } - while(i<max) { - //converts a character to a corresponding binary integer ADigit=character.digit (S.charat (i++), radix); + if(digit<0){ the Thrownumberformatexception.forinputstring (s); - } $ the if(result<multmin) { the Thrownumberformatexception.forinputstring (s); the } theresult*=Radix; - //Result-digit<limit in if(result<limit+Digit) { the Thrownumberformatexception.forinputstring (s); the } Aboutresult-=Digit; the } the } the Else{ + Thrownumberformatexception.forinputstring (s); - } the if(negative) {Bayi if(i>1){ the returnresult; the } - Else{ - Thrownumberformatexception.forinputstring (s); the } the } the Else{ the return-result; - } the}
Key points:
- The boundary value of positive number is 1 to 0x7fffffff; the boundary value of negative number is 1 to 0x80000000;
- The code handles all data as negative numbers (positive numbers) and finally handles symbolic problems;
- This variable is multmin in the method in order to Result*=radix in the loop without crossing the bounds;
JDK Source Learning Read the analysis of parseint method in-integer class (GO)