In JavaScript, we can perform 48-bit addition, subtraction, division and modulus:
In JavaScript, we can perform 48-bit addition, subtraction, division and modulus, using the native Number type:
function u48_add(a, b) {
return (a + b) % Math.pow(2, 48);
}
function u48_sub(a, b) {
return (a - b + Math.pow(2,48)) % Math.pow(2, 48);
}
function u48_div(a, b) {
return Math.floor(a / b);
}
function u48_mod(a, b) {
return a % b;
}
All these operations work, because the intermediate values can't pass Number.MAX_SAFE_INTEGER. For multiplication, though, they could:
function u48_mul(a, b) {
return (a * b) % Math.pow(2, 48);
}
So u48_mul could return incorrect results. A solution would be to use BigInt:
function u48_mul(a, b) {
return Number((BigInt(a) * BigInt(b)) % (2n ** 48n));
}
But, in most browsers, it is drastically slower. Is there any clever trick that allows us to perform 48-bit unsigned multiplication in JavaScript faster?