Skip to content

Instantly share code, notes, and snippets.

@bryc
Last active March 27, 2026 06:51
Show Gist options
  • Select an option

  • Save bryc/411ca3cfc021c1852edd589617ad2633 to your computer and use it in GitHub Desktop.

Select an option

Save bryc/411ca3cfc021c1852edd589617ad2633 to your computer and use it in GitHub Desktop.
// Optimal version of the XS1 checksum function.
function xs1cksm(data) {
let sum = [0, 0];
for(let i = 0, tmp; i < data.length; i++) {
tmp = (Math.imul(data[i], i) + sum[0] + 1994) >>> 0;
sum[1] = (sum[1] + (tmp < sum[0] ? 1 : 0)) >>> 0;
sum[0] = tmp;
}
return sum;
}
// Original JS implementation before commencing optimization - Mostly obsolete now.
function calculateChecksum(data) {
let a0 = [0, 0], a1 = [0, 0], a2 = [0, 0], a3 = [0, 0],
v0 = [0, 0], v1 = [0, 0], t0 = [0, 0], t1 = [0, 0],
s1 = [0, 0];
for(let i = 0, lo, hi, carry; i < data.length; i++) {
// LOW, HIGH
a0 = [ data[i], 0 ];
a1 = [ i, 0 ];
v0 = [ 0, a1[0] ];
v0 = [ v0[1], 0 ];
a1 = [ a1[1], 0 ];
v1 = [ 0, a0[0] ];
v1 = [ v1[1], 0 ];
a2 = [ (Math.imul(v0[0], v1[0]) >>> 0), 0 ];
a2 = [ 0, a2[0] ];
a0 = [ a0[1], 0 ];
a1 = [0xFFFFFFFF, 0xFFFFFFFF];
a1 = [ 0, a1[0] ];
a2 = [ a2[1], 0 ];
t1 = [ t1[0] & a1[0], t1[1] & a1[1] ];
a3 = [ 0xFFFF0000, 0xFFFFFFFF ];
a3 = [ a3[1], 0 ];
t1 = [ t1[0] | a2[0], t1[1] | a2[1] ];
t0 = [ 0, t0[0] ];
t1 = [ t1[0] & a3[0], t1[1] & a3[1] ];
t1 = [ t1[0] | t0[0], t1[1] | t0[1] ];
v0 = [ t1[1], 0 ];
a3 = [ t1[0] & a3[0], t1[1] & a3[1] ];
v0 = [ 0, v0[0] ];
v0 = [ a3[0] | v0[0], a3[1] | v0[1] ];
// Load intermediate value
v1 = [ s1[0], s1[1] ];
// Simulate 64-bit addition, using carry
lo = (v0[0] + v1[0] + 0x07CA) >>> 0, carry = lo < v1[0] ? 1 : 0;
hi = (v0[1] + v1[1] + carry) >>> 0;
v1 = [lo, hi];
// Save intermediate value
s1 = [ v1[0], v1[1] ];
}
return v1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment