为什么Integer.MIN_VALUE的绝对值等于Integer.MIN_VALUE [英] Why is absolute of Integer.MIN_VALUE equivalent to Integer.MIN_VALUE

查看:742
本文介绍了为什么Integer.MIN_VALUE的绝对值等于Integer.MIN_VALUE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中我说整数i = Math.abs(Integer.MIN_VALUE)。我得到与答案相同的值,这意味着 i 包含 Integer.MIN_VALUE
我也在C ++中验证了相同的内容。

In java when I say Integer i = Math.abs(Integer.MIN_VALUE). I get the same value as the answer,which means i contains Integer.MIN_VALUE. I have verified the same in C++ as well.

为什么会出现这种情况?

Why this behavior?

推荐答案

在Effective Java中阅读Joshua Bloch。

Read this in Effective Java by Joshua Bloch.

我找到了这个问题的答案,这里是解释:
计算机使用二进制算术,的逻辑java中的Math.abs 或任何语言的绝对函数如下所示:

I found the answer for this question and here is the explanation: Computers work with binary arithmentic, the logic of Math.abs in java or the absolute function in any language is like below:

if(num >= 0)
    return num;
else
    return (2's compliment of the num);

注意:如何找到2的赞美

对于给定的数字,我们首先发现它是1的赞美,然后加1。对于例如
考虑我们的号码是 10101
1的赞美= 01010
2的赞美= 01011 (在1的赞美中加1)

For a given number, we find it's 1's compliment first and then add 1 to it. For e.g. Consider our number to be 10101 1's compliment = 01010 2's compliment = 01011 (added 1 to the 1`s compliment)

现在,为了方便起见,清楚,让我们说我们的整数(带符号)大小是3位,然后这里是可以使用四位产生的数字的可能列表:

Now, for the sake of making it easy and clear, let us say that our Integer(signed) size is 3 bit, then here is the possible list of numbers which can be produced using the four bits:

000 --> 0 (0)
001 --> 1 (1)
010 --> 2 (2)
011 --> 3 (3) 
100 --> 4 (-4)
101 --> 5 (-3)
110 --> 6 (-2)
111 --> 7 (-1)

现在这是签名的,这意味着一半的数字是负数,另一半是正数(负数是第一位1的那些)。让我们从 000 开始,并尝试查找其负数,这将是 000 的两个赞美。

Now that this is signed, it means half of the numbers are negative and the other half are positive(The negative numbers are the ones with the first bit 1). Let us start from 000 and try to find its negative number, it would be the two's compliment of 000.

2's compliment of `000` = 1 + `111` = `000`
2's compliment of `001` = 1 + `110` = `111`
2's compliment of `010` = 1 + `101` = `110`
2's compliment of `011` = 1 + `100` = `101`
2's compliment of `100` = 1 + `011` = `100`
2's compliment of `101` = 1 + `010` = `011`
2's compliment of `110` = 1 + `001` = `010`  
2's compliment of `111` = 1 + `000` = `001`

从上面的演示中,我们发现2的恭维 111(-1)是001(1),同样2恭维 110(-2)是010(2),2的恭维 101(-3)是011(3)和2的恭维 100(-4)是100(-4),我们可以看到-4是使用3位可能的最小负数。

From the above demonstration, we find that 2's compliment of 111(-1) is 001(1), similarly 2's compliment of 110(-2) is 010(2), 2's compliment of 101(-3) is 011(3) and 2's compliment of 100(-4) is 100(-4) and as we can see that -4 is the smallest negative number possible using 3 bits.

这就是为什么绝对 In的原因teger.MIN_VALUE Integer.MIN_VALUE

这篇关于为什么Integer.MIN_VALUE的绝对值等于Integer.MIN_VALUE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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