Skip to content

Instantly share code, notes, and snippets.

@Meigyoku-Thmn
Last active May 17, 2021 04:15
Show Gist options
  • Save Meigyoku-Thmn/426aaf7b73cb4d68c4eea49ef1d2e323 to your computer and use it in GitHub Desktop.
Save Meigyoku-Thmn/426aaf7b73cb4d68c4eea49ef1d2e323 to your computer and use it in GitHub Desktop.
Integer overflow wrapping for Javascript (for browsers that can optimize double to integer)
const IntMask = 0xFFFFFFFF;
function iadd(a, b) {
return ((a & IntMask) + (b & IntMask)) & IntMask;
}
function isubt(a, b) {
return iadd(a, -b);
}
function imul(a, b) {
return Math.imul(a, b);
}
function idiv(a, b) {
a = +a; b = +b;
if (!Number.isFinite(a)) throw Error("Expected finite number, got a =" + a);
if (!Number.isFinite(b)) throw Error("Expected finite number, got b =" + b);
if (b == 0) throw Error("Division by zero.");
return ((a & IntMask) / (b & IntMask)) & IntMask;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment