How does Integer.toString () work internally?

I found that a similar question was asked before: how do Float.toString () and Integer.toString () work?

But this does not say how this function works internally. When I opened the internal code Integer.toString(), this is not clear to a normal junior java programmer.

Can someone explain what is going on inside in the short description?


NOTE. This was one of the interview questions I was asked recently. I had no idea how to answer such a question!

+4
source share
1 answer

arg integer.toString() Integer.toString(int i) ( integer), :

  public static String toString(int i) {
       if (i == Integer.MIN_VALUE)
           return "-2147483648";
       int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
       char[] buf = new char[size];
       getChars(i, size, buf);
       return new String(0, size, buf);
   }

, == , , . , , String stringSize() integer .

stringSize() ;

  static int stringSize(int x) {
       for (int i=0; ; i++)
           if (x <= sizeTable[i])
               return i+1;
   }

, char[] , getChars(), ;

  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
       while (i >= 65536) {
           q = i / 100;
       // really: r = i - (q * 100);
           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);
       for (;;) {
           q = (i * 52429) >>> (16+3);
           r = i - ((q << 3) + (q << 1));  // r = i-(q*10) ...
           buf [--charPos] = digits [r];
           i = q;
           if (i == 0) break;
       }
       if (sign != 0) {
           buf [--charPos] = sign;
       }
   }

stackoverflow. ( ) - getChars(), , , . , , .

+7

All Articles