【发布时间】:2016-05-11 11:46:54
【问题描述】:
超级菜鸟问题(来自一个不懂按位的人):
我在 JavaScript 中使用下面的伪随机数生成器(在我的服务器上)。
Math.seed = function(s) {
var m_w = s;
var m_z = 987654321;
var mask = 0xffffffff;
return function() {
m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
var result = ((m_z << 16) + m_w) & mask;
result /= 4294967296;
return result + 0.5;
}
}
var myRandomFunction = Math.seed(1234);
var randomNumber = myRandomFunction();
现在我想在 Java 中使用它(在我的客户端上)。这适用于 int 种子值(例如 1234 的种子在 JS 和 Java 上给出相同的数字),但我的种子值很长。如何更改按位运算符?
public class CodeGenerator {
private int m_w;
private int mask;
private int m_z;
public CodeGenerator(int seed) {
m_w = seed;
m_z = 987654321;
mask = 0xffffffff;
}
public int nextCode() {
m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
int result = ((m_z << 16) + m_w) & mask;
double result2 = result / 4294967296.0;
return (int)Math.floor((result2 + 0.5) * 999999);
}
}
【问题讨论】:
-
出于好奇...你为什么不使用docs.oracle.com/javase/7/docs/api/java/util/Random.html?
-
用long声明变量和方法。
-
@fhofmann 这会生成不同的数字。对于同一个种子,我需要它们。
-
@Niels JS 部分已在服务器上修复。我必须在客户端上使用它才能获得相同的数字。
标签: javascript java random