繁体   English   中英

getChar函数如何工作?

[英]How does the getChar function work?

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)的一部分。 开发人员是如何得出这个“神奇”的数字52429.它背后的数学是什么? 在输入81920之后,此功能不起作用。 这个神奇的数字是否仅适用于特定范围的输入,如果是这样,为什么?

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

// 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的“ 使用乘法不变整数 ”一书中找到。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM