我今天正在进行编码测试,目标是在 JavaScript 中添加 2 个字符串的整数表示时捕获所有边缘情况。我无法得到的一个案例是如何检测存储在 IEEE 754 数字中的总和的上溢/下溢。
通常,在 C 中,我会查看数字的二进制表示,但在 JavaScript 中,我只能查看 32 位的整数值。
这是我的代码:
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 现在有一个 Number.MAX_SAFE_INTEGER
实际上,由于 float 学的工作方式,Javascript 中的整数是 53 位信息。
上次我需要做类似的事情时我做了......
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 想了想,还是比较容易说:
var MAX_INT = Math.pow(2, 53) -1;
var MIN_INT = -MAX_INT;
因为这是您知道的最大的 INT,还没有溢出。
关于javascript - 如何检测 JavaScript 算术运算中的数字溢出/下溢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23164706/