整数溢出到负数 [英] Integer overflow to negative number

查看:79
本文介绍了整数溢出到负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此链接,我了解到在IE8中,新元素的索引将如果创建的数组的索引大于2147483647,则为负数。

According to this link, I learned that in IE8 the the new element's index will be a negative number if the array was created with an index greater than 2147483647.

并且有以下示例:

function test() { 
    var arr = new Array();         
    arr[2147483650] = 10000; 
    arr.push(10);     
    document.write(arr["-2147483645"] == 10); 
} 
test();

我不明白的是,数组中新添加的元素为何具有索引 -2147483645 ,我了解负面因素,我只是不知道如何知道新索引为 2147483645 ,而不是 -2147483644 -2147483651 ...

What I don't understand is, how come the newly added element of the array have the index of -2147483645, I understand the negative part, I just don't know how to know that the new index is 2147483645, not -2147483644 or -2147483651 ...

推荐答案

当以32位表示数字时,最高位用作符号位,因此当以二进制表示诸如2147483647的数字时,则为

When representing a number in 32 bits, the highest bit is used as a sign bit, so when representing a number like 2147483647 in binary, it is

01111...111

其中有31个1。当我们再添加一个,我们得到

where there are 31 1's. When we add one more to that, we get

10000...000

其中有31个0。因此,我们将符号位跳闸为一个表示负数的位。但是,由于需要避免两次代表0,所以我们将数字包装起来,所以它不是代表-0,而是代表负2147483648(不是2147483647,因为正边需要代表0,但是负边则不需要代表0)得到一个额外的负数)。

where there are 31 0's. Thus we have tripped the sign bit to be one indicating a negative number. However, because of a need to avoid representing 0 twice, we wrap the number, so instead of representing -0, this represents negative 2147483648 (not 2147483647 because the positive side needed to represent 0, but as the negative side doesn't, we get one "extra" negative number).

每次我们向其添加一个,都会增加二进制表示形式,并通过负数递减

Each time that we add one to this, it will increase the binary representation, which counts down through the negative numbers

1000...00 = -2147483648 // this is 2147483648
1000...01 = -2147483647 // this is 2147483649
1000...10 = -2147483646 // this is 2147483650

。因此2147483650被包装为-2147483646,因此,将其设置为-2147483645。

and so on. Thus 2147483650 gets wrapped to -2147483646 and therefore, one more than that gets set to -2147483645.

请参见此处了解详情。

这篇关于整数溢出到负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆