七进制字符串转十进制:
package test;
public class Change {
public static void main(String[] args) {
String str = "1234";
System.err.println(parseInt(str,7));
}
private static int parseInt(String str4, int radix) {
/* 异常情况1:字符串为null */
if (str4 == null) {
throw new IllegalArgumentException("字符串为null!");
}
int length = str4.length(), offset = 0;
/* 异常情况2:字符串长度为0 */
if (length == 0) {
throw new IllegalArgumentException("字符串长度为0!");
}
boolean negative = str4.charAt(offset) == '-';
if (negative) {
throw new IllegalArgumentException("字符串位负数!");
}
int result = 0;
char[] temp = str4.toCharArray();
while (offset < length) {
char digit = temp[offset++];
int currentDigit = digit - '0';
/* 一位一位判断,是否在0~7之间,否则为非法输入 */
if (currentDigit < radix && currentDigit >= 0) {
/* 2种溢出情况,第1种,当前的resut已经等于Integer.MAX_VALUE / 10,看个位数是否在范围内 */
if (result == Integer.MAX_VALUE / radix
&& currentDigit > Integer.MAX_VALUE % radix) {
throw new IllegalArgumentException("字符串溢出!");
/* 2种溢出情况,第2种,当前的resut已经大于Integer.MAX_VALUE / 10,不论个位是什么,都溢出 */
} else if (result > Integer.MAX_VALUE / radix) {
throw new IllegalArgumentException("字符串溢出!");
}
/*关键部分*/
result = result * radix + currentDigit;
} else {
throw new IllegalArgumentException("字符串字符不在0~"+radix+"!");
}
}
return result;
}
}
给定一个整数,将其转化为其他进制,并以字符串形式输出。
二进制:Integer.toBinaryString();
八进制:Integer.toOctalString();
十六进制:Integer.toHexString();
https://blog.youkuaiyun.com/brillianteagle/article/details/50513668