超级noob问题(来自一个不理解按位的人):
我在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);
}
}
答案 0 :(得分:0)
在Java中,您需要将种子掩码为unsigned int,然后生成与JS版本相同的数字。
新构造函数:
public CodeGenerator(long seed) {
mask = 0xffffffff;
m_w = (int) (seed & mask);
m_z = 987654321;
}
答案 1 :(得分:0)
您是否尝试过只声明种子和第一个结果?
public class CodeGenerator {
private long m_w;
private int mask;
private int m_z;
public static void main(String... a){
System.out.println(new CodeGenerator(1234).nextCode()); //result = 237455
System.out.println(new CodeGenerator(1234567891234L).nextCode()); //result = 246468
}
public CodeGenerator(long 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;
long result = ((m_z << 16) + m_w) & mask;
double result2 = result / 4294967296.0;
return (int)Math.floor((result2 + 0.5) * 999999);
}
}