如何在JavaScript算术运算中检测数字上溢/下溢?

编程入门 行业动态 更新时间:2024-10-11 09:28:12
本文介绍了如何在JavaScript算术运算中检测数字上溢/下溢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我今天正在进行编码测试,目标是在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算术运算中检测数字上溢/下溢?

本文发布于:2023-10-24 20:48:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524961.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上溢   算术   数字   如何在   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!