如何将 JavaScript BigInt 拆分为 5 位块?

How to split JavaScript BigInt into 5-bit chunks?

基于这个问题 ,我让它在 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);