Java Integer.parseInt(String s, int radix) 实现A、B、C分别代表10,11,12转换

tech2026-04-15  2

在实际业务过程中我们常遇到 Y 一码代表月份,A,B,C 分别代表10、11、12月

public static void main(String[] args) { //A B C 分别代表 10,11,12 String M ="A"; int month = Integer.parseInt(M, 13); System.out.println("month = " + month); }

parseInt(String s, int radix) 源码如下:

/** * Parses the string argument as a signed integer in the radix * specified by the second argument. * * <p>Examples: * <blockquote><pre> * parseInt("0", 10) returns 0 * parseInt("473", 10) returns 473 * parseInt("+42", 10) returns 42 * parseInt("-0", 10) returns 0 * parseInt("-FF", 16) returns -255 * parseInt("1100110", 2) returns 102 * parseInt("2147483647", 10) returns 2147483647 * parseInt("-2147483648", 10) returns -2147483648 * parseInt("2147483648", 10) throws a NumberFormatException * parseInt("99", 8) throws a NumberFormatException * parseInt("Kona", 10) throws a NumberFormatException * parseInt("Kona", 27) returns 411787 * </pre></blockquote> */ public static int parseInt(String s, int radix) throws NumberFormatException { /* * WARNING: This method may be invoked early during VM initialization * before IntegerCache is initialized. Care must be taken to not use * the valueOf method. */ 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, len = s.length(); // 设置初始位置和字符串的长度 int limit = -Integer.MAX_VALUE; int multmin; int digit; if (len > 0) { // 字符串的长度必须大于零 char firstChar = s.charAt(0); // 获得字符串的第一个字符 if (firstChar < '0') { // Possible leading "+" or "-" if (firstChar == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (firstChar != '+') // 如果不为++的话就报错 throw NumberFormatException.forInputString(s); // 字符串的长度为1但是又不是数字, 出错 if (len == 1) // Cannot have lone "+" or "-" throw NumberFormatException.forInputString(s); i++; } multmin = limit / radix; /* * 下面的过程其实很好理解, 以8进制的"534"为例 * (-5*8-3)*8-4 = -348, 根据符号位判断返回的是348 */ while (i < len) { // 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); } return negative ? result : -result; // 根据符号位来判断返回哪一个 }

 

最新回复(0)