getChar函数如何工作?

use*_*909 3 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;
}
Run Code Online (Sandbox Code Playgroud)

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

And*_*eas 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
//
Run Code Online (Sandbox Code Playgroud)

因此,您的问题的答案可以在T Gralund,P Montgomery的" 使用乘法不变整数 "一书中找到.

  • @QuestionEverything至于为什么,请阅读这本书.但请注意,在JDK8中,它仅限于"65536".请参阅第453行的评论:http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Integer.java#l433 (2认同)