How make uint32 multiplications in javascript without loosing precision ?
I am trying implement C algorithm in javascript.
uint32 key = (val * 134775813) + 1;
So, all higher bytes will be lost in result.
I tried browser console:
> a1 = 591751271
591751271
> a2 = 134775813
134775813
> a4 = (a1 * a2) + 1;
79753758642808320
I made same calculation with python
Python 3.7.9 (default, Aug 18 2020, 06:22:45)
[GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a1=591751271
>>> a2=134775813
>>> a4 = (a1 * a2) + 1
>>> print(a4)
79753758642808324
Looks similar but I am specially interested those lower bytes. Can anyone point me right direction.
I know there are built in BigInt objects, but really you cant make any operations with those.
Thanks to ASDFGerte . Who pointed me towards Math.imul function.
I came up with this one liner and it performed perfectly.
const uMul = (a,b) => Math.imul(a, b) >>> 0;
MDN site has polyfill function and with small change it does the same.
const uMul = (a, b) => {
const aHi = (a >>> 16) & 0xffff;
const aLo = a & 0xffff;
const bHi = (b >>> 16) & 0xffff;
const bLo = b & 0xffff;
// the shift by 0 fixes the sign on the high part
return (aLo * bLo) + (((aHi * bLo + aLo * bHi) << 16) >>> 0);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.