I'm trying to transcript the following C code to JavaScript, but I'm not getting it.
#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));
}
}
This was my try but I got different results from the C code:
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) );
}
How can I do this?
You can use BigInt in javascript with BigInt() and n appended to the number literals:
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));
}
Output:
0n
2116118n
89401895n
379337186n
782977366n
196130996n
198207689n
1046291021n
1131187612n
975888346n
500746873n
1785185521n
2000878121n
1219898729n
1194203485n
109160704n
1647229822n
40619231n
541938462n
640373553n