将 C 按位​​运算转录为 JS

Transcript a C bitwise operation to JS

我正在尝试将以下 C 代码转录为 JavaScript,但我没听懂。

#include <stdio.h>
#include <stdlib.h>

long long seed;
int next(int bits) {
 seed=(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
 return (int)(seed >> (48 - bits));
}

void main (void) {
    seed = 0;
    for (int i=0;i<20;i++) {
        printf ("%d\n", next(31));
    }
}

这是我的尝试,但我从 C 代码中得到了不同的结果:

let seed;
function next(bits) {
 seed = (seed * 0x5DEECE66D + 0xB) & ((1 << 48) - 1);
 return (seed >> (48 - bits));
}

seed = 0;
for ( let i=0; i<20; i++ ) {
    console.log( next(31) );
}

我该怎么做?

您可以在 javascript 中使用 BigInt,将 BigInt() 和 n 附加到数字文字:

let seed = 0n;

function next(bits) {
  seed = (seed * BigInt(0x5deece66d) + BigInt(0xb)) & ((1n << 48n) - 1n);
  return seed >> (48n - bits);
}

for (let i = 0; i < 20; i++) {
  console.log(next(31n));
}

输出:

0n
2116118n
89401895n
379337186n
782977366n
196130996n
198207689n
1046291021n
1131187612n
975888346n
500746873n
1785185521n
2000878121n
1219898729n
1194203485n
109160704n
1647229822n
40619231n
541938462n
640373553n