1. 區(qū)別
toString方法將數(shù)字轉(zhuǎn)為有符號(hào)數(shù)對(duì)應(yīng)的字符串塑崖,toUnsignedString是將數(shù)字轉(zhuǎn)為有符號(hào)數(shù)對(duì)應(yīng)的字符串。
2. toString(long i, int radix)
public static String toString(long i, int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
if (radix == 10)
return toString(i);
char[] buf = new char[65];
int charPos = 64;
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = Integer.digits[(int)(-(i % radix))];
i = i / radix;
}
buf[charPos] = Integer.digits[(int)(-i)];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (65 - charPos));
}
- 當(dāng)要轉(zhuǎn)為十進(jìn)制的時(shí)候燕侠,直接用toString方法,toString里面主要是用了getChars方法,我們?cè)谥?a target="_blank" rel="nofollow">http://www.chenchen.zone/articles/2018/09/27/1538041030708.html講過(guò)。
public static String toString(long i) {
if (i == Long.MIN_VALUE)
return "-9223372036854775808";
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}
- 當(dāng)非10進(jìn)制的時(shí)候
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = Integer.digits[(int)(-(i % radix))];
i = i / radix;
}
buf[charPos] = Integer.digits[(int)(-i)];
if (negative) {
buf[--charPos] = '-';
}
這里有個(gè)比較巧妙的地方我開(kāi)始沒(méi)有想通诊杆,就是為什么把數(shù)字都統(tǒng)一轉(zhuǎn)為負(fù)數(shù)來(lái)處理呢捉腥。首先肯定是統(tǒng)一轉(zhuǎn)為正數(shù)或者負(fù)數(shù)處理氓拼,那為什么是負(fù)數(shù)。答案就是有負(fù)數(shù)數(shù)字負(fù)數(shù)比負(fù)數(shù)多一個(gè)數(shù)字抵碟,比如64位系統(tǒng)Long的范圍是-9223372036854775808 ~ 9223372036854775807桃漾。當(dāng)遇到Long最大正數(shù)9223372036854775807時(shí),可以轉(zhuǎn)為-9223372036854775807拟逮,但是當(dāng)你遇到Long最小負(fù)數(shù)-9223372036854775808時(shí)轉(zhuǎn)為正數(shù)就會(huì)溢出呈队。所以統(tǒng)一轉(zhuǎn)為負(fù)數(shù)處理可以多處理一個(gè)數(shù)。
3. toUnsignedString(long i, int radix)
public static String toUnsignedString(long i, int radix) {
if (i >= 0)
return toString(i, radix);
else {
switch (radix) {
case 2:
return toBinaryString(i);
case 4:
return toUnsignedString0(i, 2);
case 8:
return toOctalString(i);
case 10:
/*
* We can get the effect of an unsigned division by 10
* on a long value by first shifting right, yielding a
* positive value, and then dividing by 5. This
* allows the last digit and preceding digits to be
* isolated more quickly than by an initial conversion
* to BigInteger.
*/
long quot = (i >>> 1) / 5;
long rem = i - quot * 10;
return toString(quot) + rem;
case 16:
return toHexString(i);
case 32:
return toUnsignedString0(i, 5);
default:
return toUnsignedBigInteger(i).toString(radix);
}
}
}
- 正數(shù)toString和toUnsignedString是一樣的
- 負(fù)數(shù)使用toUnsignedString0方法唱歧,這個(gè)我們之前http://www.chenchen.zone/articles/2018/09/25/1537868505126.html講過(guò)
作者 @沒(méi)有故事的老大爺
一定要專注宪摧,這樣才會(huì)忘記痛苦