如何在JavaScript算术运算中检测数字上溢/下溢? [英] How to detect numeric overflow/underflow in JavaScript arithmetic operations?
问题描述
我今天正在进行编码测试,目标是在JavaScript中添加2个字符串整数表示时捕获所有边缘情况。我无法得到的一个案例是如何检测存储在IEEE 754数字中的总和的上溢/下溢。
I was doing a coding test today, the goal was to catch all edge cases when adding 2 integer representations of strings in JavaScript. One case I could not get was how to detect overflow/underflow for the sum stored in the IEEE 754 numeric.
通常,在C中,我会查看数字的二进制表示,但在JavaScript中,我只能查看32位的整数值。
Normally, in C, I'd look at the binary representation of the numeric, but in JavaScript, I can only look at 32 bits worth of the integer value.
这是我的代码:
function string_add(a, b) {
if (arguments.length !== 2)
throw new Error('two arguments expected as input');
// ensure we have strings
if (typeof a !== 'string' || typeof b !== 'string')
throw new Error('bad parameter types');
// ensure we do not have empty strings
if (a.length === 0 || b.length === 0)
throw new Error('an empty string is an invalid argument');
// ensure we have integer arguments
if (0 !== (+a % 1) || 0 !== (+b % 1))
throw new Error('expected numeric integer strings for arguments');
var sum = +a + +b; // create numeric sum of a and b.
sum+=''; // convert numeric sum to string
return sum;
}
提前致谢。
推荐答案
实际上,由于浮点数学运算的方式,Javascript中的整数是53位信息。
Actually, integers in Javascript are 53 bits of information due to the way floating point math works.
最后一次我需要做类似的事情......
The last time I needed to do something similar I did...
var MAX_INT = Math.pow(2, 53);
var MIN_INT = -MAX_INT;
var value = MAX_INT * 5;
if (value >= MAX_INT) {
alert("Overflow");
}
// Note. you have to use MAX_INT itself as the overflow mark because of this:
value = MAX_INT+1;
if (value > MAX_INT) {
alert("Overflow test failed");
}
编辑在考虑之后,它会是更容易说:
EDIT After thinking about it, it would be easier to say:
var MAX_INT = Math.pow(2, 53) -1;
var MIN_INT = -MAX_INT;
因为那是你知道的最大的INT没有溢出。
since that is the largest INT that you know hasn't overflowed.
这篇关于如何在JavaScript算术运算中检测数字上溢/下溢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!