String ret = Integer.toBinaryString(-5);
System.out.println(ret);
DecimalFormat df = new DecimalFormat ("00000000,00000000,00000000,00000000");
System.out.println(df.format(Integer.valueOf(ret)));
主要是int/Integer是32位整型,按十进制看最大能表示的正整数只到
2147483647
而Integer.valueOf(str)是将字符串以10进制方式解释,看看-5得到的binaryString:
11111111111111111111111111111011
显然要比int/Integer能表示的范围大,因而出错。
double/Double能表示的范围非常大,但是在绝对值很大或者很小的时候精度都会降低。仍然是因为Double.valueOf(str)也是将字符串以十进制解释,转换之后得到的是最接近给定字符串所指的数字的双精度浮点数,所以值与原本字符串所指定的不一定相同。
如果用Integer.valueOf(str, radix)的重载就可以指定转换时使用的进制。例如说把radix指定为2就可以指定解析表示二进制数的字符串:
[code="java"]Integer.valueOf("100"); // 4[/code]
但是用它来转换由Integer.toBinaryString(i)得到的字符串仍然是不可行的,因为这个方法得到的是无符号二进制数的字符串表示,而Integer.parseInt(str, radix)或者Integer.valueOf(str, radix)都接受的是带符号的数字的字符串表示。
可以参照Integer.parseInt(str, radix)的实现代码:
[code="java"] public static int parseInt(String s, int radix)
throws NumberFormatException
{
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, 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;
}
}[/code]
啊前面手滑了,有Integer.valueOf(str, radix)那个例子是:
[code="java"]Integer.valueOf("100", 2); // 4[/code]