Last active
May 17, 2021 04:15
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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