【发布时间】:2017-12-08 16:39:45
【问题描述】:
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 后,此功能不起作用。这个幻数是否只适用于特定范围的输入,如果是,为什么?
【问题讨论】:
-
这个方法属于什么类?
-
@Seelenvirtuose 哎呀,OP 更新了。它在 java.lang.Integer
-
我只在
java.lang.Integer(JDK7和JDK8)中看到了一个方法static void getChars(int i, int index, char[] buf)。困惑... -
@Seelenvirtuose 在 JDK8 中,在第 456 行:hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/…(注意这是一个
private方法) -
@Seelenvirtuose 问题说显示的代码是“基于 部分 java.lang.Integer.getChars(int)”。问题是询问魔术数字
52429。我只是指出,在 JDK8 中,该幻数位于第 456 行。作为my answer says,幻数来自一本书。