如何将JavaScriptBigInt拆分为5位块



基于这个问题,如何让这个PRNG生成范围内的数字,我正在让它支持JavaScript中的BigInt(大值(,我认为我做得对(如果我做得不对,请纠正我(:

const fetch = (x, o) => {
if (x >= o) {
return x
} else {
const v = (x * x) % o
return (x <= (o / 2n)) ? v : o - v
}
}
const fetchLarge = (x) => fetch(x, 43214321432143214321432143214321432143214321n)
// the last number can be anything.
const buildLarge = (x, o) => fetchLarge((fetchLarge(x) + o) % BigInt(Math.pow(32, 31)) ^ 101010101010104321432143214321n)
const j = 432143213214321432143214321432143214321n; // If you don't want duplicates, either i or j should stay fixed
let i = 1n
let invalid = [];
let valid = new Set;
while (i) {
let x = buildLarge(i, j);
if (valid.has(x)) {
invalid.push([i, j, x]);
} else {
valid.add(x);
}
console.log(x)
i++;
}
console.log("invalid:", invalid);
console.log("valid:", [...valid]);
console.log("count of valid:", valid.size);

旁注:永远不应该有invalid

但主要的问题是,给定x的值,如40531205068036774067539981357810868028938588n,如何将其划分为5位值的数组(0-31之间的整数数组(?

它和做x.toString(32),然后把这些字母转换成索引或其他什么一样简单吗?不确定我这样做是否正确。

要创建一个数字在0-31之间的数组,您只需划分并收集余数(然后将其转换为标准数字(:

function createArray(n, mod=32n) {
if (!n) return [0];
let arr = [];
while (n) {
arr.push(Number(n % mod));
n /= mod;
}
return arr;
}
let result = createArray(40531205068036774067539981357810868028938588n);
console.log(result);

最新更新