I want move some of bit toward right in javascript, but I found result was not right because I wrote a test program by C language to contradistinction.
I spend whole day who had’t found correct way. please, Could you tell me that right way.
const poly = BigInt('0x42F0E1EBA9EA3693');
let crc = BigInt(1);
for (let k = 0; k < 8; k++) {
crc = poly ^ (crc >> 1n);
const c1 = crc & 0xFFFFFFFFn;
console.log('crc:', c1.toString(16).padStart(8, '0'));
}
// output:
// crc: a9ea3693
// crc: 7d1f2dda
// crc: 9765a07e
// crc: e258e6ac
// crc: 58c645c5
// crc: 05891471
// crc: ab2ebcab
// crc: 7c7d68c6
#include <stdio.h>
#include <stdint.h>
int main()
{
uint64_t poly = 0x42F0E1EBA9EA3693;
unsigned int crc = 1;
for (unsigned int k = 0; k < 8; k++)
{
crc = poly ^ (crc >> 1);
printf("crc: %xn", crc);
}
return 0;
}
// output
// crc: a9ea3693
// crc: fd1f2dda
// crc: d765a07e
// crc: c258e6ac
// crc: c8c645c5
// crc: cd891471
// crc: cf2ebcab
// crc: ce7d68c6
I try used Uint8Array to do it instead of BigInt, but result still error. How can i do ? How do it ? result can like c language.
2
Answers
Your JS
crc
is aBigInt
of unlimited width. Your Ccrc
is an unsigned int of 32 bits. This means the higher 32 bit of yourpoly
are never used in thecrc = poly ^ (crc >> 1);
calculation. You want 64 bits there to get the same result:Your JS loop fails to update
crc
in the same way as the C program. To achieve the same result as the C program, replacewith
This causes the bits of higher-precision to be dropped, just like in the C program.