简体   繁体   English

如何计算在Javascript中以字符串形式给出的64位整数的除法余数

[英]How to calculate division remainder of 64bit integer given as string in Javascript

Is there fast and simple way to make an "%" operation for 64bit integer given as "string" (for example "1bed658e4cbba3a7")?有没有快速简单的方法来对作为“字符串”给出的 64 位整数进行“%”操作(例如“1bed658e4cbba3a7”)?

I know that Google Closure Library has such function, but I'd prefer not to use any external libraries, and moreover internally it works as three operations (division, multiplication and substraction) and seems to be not optimal.我知道谷歌闭包库有这样的功能,但我不想使用任何外部库,而且在内部它作为三个操作(除法、乘法和减法)工作,似乎不是最优的。

Added : Problem is that JavaScript cannot handle 64bit integers without loosing precision.补充:问题是 JavaScript 无法在不失去精度的情况下处理 64 位整数。 For details see this question有关详细信息,请参阅此问题

If you have an upper bound on the right-hand operand, then you can split the 64-bit int into two parts, and calculate the modulus from that.如果右侧操作数有上限,则可以将 64 位 int 分为两部分,并从中计算模数。 (It's three % operations, and I don't know whether that's fast enough for your purposes). (这是 3% 的操作,我不知道这对于您的目的是否足够快)。

For example, if you want to calculate x % c, and c < 2^32, then you can split x into two parts, a and b, and calculate:例如,如果要计算 x % c,并且 c < 2^32,则可以将 x 拆分为 a 和 b 两部分,并计算:

(a * 2^32 + b) % c = (((a % c)* (2^32 % c)) + b) % c

This depends on c being small, though.不过,这取决于 c 是否小。 If it is also close to 64 bits, then you will want to look for other methods.如果它也接近 64 位,那么您将需要寻找其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM