gpt4 book ai didi

javascript - 类似 PRNG 的种子哈希函数

转载 作者:行者123 更新时间:2023-11-28 01:07:05 25 4
gpt4 key购买 nike

我希望两个客户端使用相同的“种子”通过输入时间戳或长数字来生成相同的数字,并像使用 random() 一样返回 float 。

例如,使用函数:hasher(String seeds, long input);

 hasher("StackOverflow", 1000000010); //returns 0.57217329503213..
hasher("StackOverflow", 1000000010); //returns 0.57217329503213...
hasher("StackOverflowz", 1000000010); //returns 0.15689784654554...
hasher("StackOverflow", 97494849465); //returns 0.456944151561...

它确实不应该是安全的或私密的,而只是足够随机。我认为我可以使用位操作,但我绝不是散列或位操作方面的专家。

我意识到种子与组合种子和输入相比几乎是多余的,但我认为了解在不影响可靠性的情况下实现种子的最佳方法会有所帮助。有什么想法吗?

谢谢。

最佳答案

我做了一个小实现,但要注意 JavaScript 与我的主要语言相去甚远。该代码需要 CryptoJS 来实现哈希功能。

function hasher(a, b) {
hash = fromHex(CryptoJS.enc.Hex.stringify(CryptoJS.SHA256(a + b)));
// warning: only about 32 bit precision
hashAsDouble = intFromBytes(hash.slice(0, 4)) * (1.0 / 4294967296.0);
return hashAsDouble;
}

function fromHex(hex) {
a = [];
for (var i = 0; i < hex.length; i += 2) {
a.push("0x" + hex.substr(i, 2));
}
return a;
}

function intFromBytes(x) {
if (x.length != 4) {
return null;
}

var val = 0;
for (var i = 0; i < x.length; i++) {
val = val << 8;
val = val + (x[i] & 0xFF);
}
return toUint32(val);
}

function modulo(a, b) {
return a - Math.floor(a / b) * b;
}

function toUint32(x) {
return modulo(toInteger(x), Math.pow(2, 32));
}

function toInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}

关于javascript - 类似 PRNG 的种子哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24941475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com