toString()
public String toString() {
return toString(value);
}
final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE };
public static String toString(int i) {
//1
if (i == Integer.MIN_VALUE)
return "-2147483648";
//2
int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
//3
char[] buf = new char[size];
//4
getChars(i, size, buf);
return new String(buf, true);
}
static int stringSize(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}
1、如果Integer的value值正好是 Integer.MIN_VALUE 直接返回 “-2147483648” 节省时间。
2、得到integer值的十进制的长度,如果负数先求出绝对值的长度,然后再长度加1,因为负数的符号位占一位。 stringSize 非常的巧妙的来获取整数的长度,根据sizeTable数组的值区间来确定,字符串长度。
3、根据十进制的长度,声明一个char数组。
4、填充char数组
static void getChars(int i, int index, char[] buf) {
int q, r;
int charPos = index;
char sign = 0;
if (i < 0) {
sign = '-';
i = -i;
}
// Generate two digits per iteration 每次迭代生成两位数字
// 1
while (i >= 65536) {
//除以100求得商q
q = i / 100;
// really: r = i - (q * 100);
//求得余数r
r = i - ((q << 6) + (q << 5) + (q << 2));
i = q;
//填充个位数字符
buf [--charPos] = DigitOnes[r];
//填充十位数字符
buf [--charPos] = DigitTens[r];
}
// Fall thru to fast mode for smaller numbers
// assert(i <= 65536, i);
//2
for (;;) {
//i除以10的商 q
q = (i * 52429) >>> (16+3);
//i 减去商乘以10,得余数r
r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
//buf填充字符
buf [--charPos] = digits [r];
i = q;
if (i == 0) break;
}
if (sign != 0) {
buf [--charPos] = sign;
}
}
final static char [] DigitTens = {
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
} ;
final static char [] DigitOnes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
} ;
1、分成两部分来计算,大于65536部分,每次除以100的余数
利用DigitOnes,DigitTens两个数组获取个位数及十位数字符
2、小于65536部分,除10求余,根据余数获取对应的字符。
网友评论