getChar函数如何工作?

时间:2017-07-05 06:55:42

标签: java algorithm binary

private static char[] getChars(int i) {
    char buf[] = new char[32];
    int q;
    for (int j = 31; j >= 0; j--) {
         q = (i * 52429) >>> (19);
         int r = i - ((q << 3) + (q << 1));
         buf[j] = (char) (r + '0');
         i = q;
         if (i == 0)
             break;
    }

 return buf;
}

上面的代码基于java.lang.Integer.getChars(int)的一部分。开发人员是如何提出这个&#34;魔术&#34;编号52429.背后的数学是什么?在输入81920之后,此功能不起作用。这个神奇的数字是否仅适用于特定范围的输入,如果是这样,为什么?

1 个答案:

答案 0 :(得分:5)

如果您搜索源代码,您将找到该数字的第二个实例:

// I use the "invariant division by multiplication" trick to
// accelerate Integer.toString.  In particular we want to
// avoid division by 10.
//
// The "trick" has roughly the same performance characteristics
// as the "classic" Integer.toString code on a non-JIT VM.
// The trick avoids .rem and .div calls but has a longer code
// path and is thus dominated by dispatch overhead.  In the
// JIT case the dispatch overhead doesn't exist and the
// "trick" is considerably faster than the classic code.
//
// TODO-FIXME: convert (x * 52429) into the equiv shift-add
// sequence.
//
// RE:  Division by Invariant Integers using Multiplication
//      T Gralund, P Montgomery
//      ACM PLDI 1994
//

所以,问题的答案可以在T Gralund,P Montgomery的书Division by Invariant Integers using Multiplication中找到。