2的补充怪异

时间:2012-10-17 14:43:03

标签: math

当我意识到时,我正在做练习:

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

我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

错误的地方是(2'complement of 1)不是(1's complement of 1 + 1)

你需要在处理操作数的方式上保持一致,要么它们表示两个补码值,要么表示一个补码的值,不能将两者混合使用。

它只是一种惯例,非常类似于各种编程语言中有符号和无符号标量类型之间的区别。您不能在同一算术运算中混合有符号和无符号标量,并期望结果是正确的。

具体 :(假设8位整数大小,参数只与1的comp。或2的comp。中允许的值范围相同)。
在一个补码约定中,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.  
相关问题