添加和减去两个补码

6 binary twos-complement

使用六位一和二的补码表示我试图解决以下问题:

12 - 7 
Run Code Online (Sandbox Code Playgroud)

现在,我先拿二进制12和二进制7.

12 = 001100 - 6 bit 
7 =  000111 - 6 bit
Run Code Online (Sandbox Code Playgroud)

然后,我会将这个位翻转为两个补码并添加一个吗?

12 = 110011 ones complement 
     +    1
    -------
     001101

7  = 111000 ones complement 
    +     1
   ---------
      111001
Run Code Online (Sandbox Code Playgroud)

然后,将这两个补码加在一起

 001101
+111001
-------
1000110 = overflow? discard the last digit?  If so I get 5
Run Code Online (Sandbox Code Playgroud)

现在,如果我有一个像

-15 + 2
Run Code Online (Sandbox Code Playgroud)

如果它是零,我会在MSB上添加一个符号幅度?

喜欢:

-15 = 001111 6 bit
Run Code Online (Sandbox Code Playgroud)

在翻转位之前,我会在这里添加1吗?

  = 101111
Run Code Online (Sandbox Code Playgroud)

Sch*_*ler 15

使用二进制补码表示负值具有减法和加法相同的好处.你的情况,你能想到的12 - 7作为12 + (-7).因此,您只需要找到-7的二进制补码表示并将其添加到+12:

12  001100
-7  111001   -- to get this, invert all bits of 7 (000111) and add 1
----------
 5 1000101
Run Code Online (Sandbox Code Playgroud)

然后丢弃进位(表示溢出),你得到你的结果:000101等于预期的5.

对于您的示例-15 + 2,只需按照相同的过程获得-15的二进制补码表示:

15  001111
    110000   -- inverted bits
    110001   -- add 1
Run Code Online (Sandbox Code Playgroud)

现在像往常一样添加:

-15  110001
  2  000010
-----------
res  110011
Run Code Online (Sandbox Code Playgroud)

要确定它res确实等于-13,您可以看到它是负数(MSB设置).对于幅度,转换为正(反转位,加1):

res  110011
     001100  -- inverted bits
     001101  -- add 1
Run Code Online (Sandbox Code Playgroud)

因此,如预期的那样,幅度为13.