2012-10-17 74 views
1

我在做一个锻炼; Tibial当我意识到:2的补古怪

a-2 = a-1-1 = a + (2'complement of 1) - 1 
    = a + (1's complement of 1 + 1) - 1 
    = a + 1's complement of 1 
    = a + 0 
    = a 

所以最终

a-2 = a 

我干了什么错在这里做什么?

回答

3

你错了的是(2'complement of 1)不是(1's complement of 1 + 1)

您需要对待操作数的方式保持一致,要么它们表示二进制补码值,要么一个补码值,两者混合是不好的。

这仅仅是一个约定,非常类似于各种编程语言中有符号和无符号标量类型之间的区别。您不能在相同的算术运算中混合使用有符号和无符号的标量,并期望结果是正确的。

具体的 :(假设8位整数大小,参数是相同的,只有在1的补偿或2的补偿允许的值的范围不同)。
在补码约定中,1's complement of 111111110它表示值254,它是不能用补码约定(具有8比特整数)表示的值;您可以用二进制补码表示的值范围是-128到+127。

在你推导,您将可以因此写作是无效的操作,让我们使用十进制值换算公式改写:

a-2 = a-1-1   // OK, we start in 2's complement convention 
    = a + (-1) - 1  // OK, we're still in 2's complement convention 
    = a + (+255) - 1 // OOPS: we're switching our interpretation of the operand 
         // in parenthesis, we now understand it to be in 1's comp. 
         // but... wait! 255 is not in the range of the 2's comp. 
         // convention we started with. 
+0

这取决于什么“是”的意思是。 – geoffspear

+0

为什么(2的补充)不是(1 + 1的补码)? – Chin

+0

@Chin:看我的编辑。 1'_in 2的comp convention_的2的补码表示-1。相同的位模式意味着+255(或+65535或16位和其他整数大小的其他大值)_in 1的comp。惯例_。然而255或254不是2的comp中有意义的值。约定(你可以拥有的最大值是127(或32767或更多,大约是1的补码所允许的最大正数的一半),因此你的推导是不正确的,你切换_convention_。 – mjv