String s = "0xAA";
int ans = Integer.decode(s);
System.out.println(ans);
如果说需要将8进制数或者16进制数转成10进制,直接把数变成String传进Integer.decode就行。
public static Integer decode(String nm) throws NumberFormatException {
int radix = 10; //表示进制,10为10进制
int index = 0;
boolean negative = false;
Integer result;
if (nm.isEmpty())
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Integer.valueOf(nm.substring(index), radix);
result = negative ? Integer.valueOf(-result.intValue()) : result;
} catch (NumberFormatException e) {
// If number is Integer.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Integer.valueOf(constant, radix);
}
return result;
}
Integer.decode()的源码中可以看到,它对16进制数前的0x有一个判断。
在中间的主要代码中我发现,主要用Integer.valueOf()方法进行进制转换,前提是把数字的前缀去掉。
String s = "0xAA";
int ans = Integer.valueOf(s.substring(2),16);
System.out.println(ans);
处理字符串的一些方法总结:
s.substring(index)从index开始的子串
s.charAt(i)
Integer.decode()
Integer.valueOf()