0

我似乎找到的所有关于如何找到 1s(翻转正数位)和 2s(翻转正数二进制位并加 1)补码的答案似乎都没有回答我的问题。

我的家庭作业要求找到一个负数的补码。所以不是从一个正数开始,需要找出它的负数是什么,而是给我一个负数并要求找到它的补码。

一个愚蠢的想法是,我是否找到正值二进制值,然后翻转位以获得负数,然后再次翻转以找到负数的 1s 补码?

4

1 回答 1

4

It doesn't matter if your starting number is positive or negative - in a two's complement system, -x is the same as ~x + 1. If your original number is positive, the result will be negative, and if the original number is negative, the result will be positive. 8-bit example - binary means 2's complement binary:

x (decimal) | -x (decimal) | x (binary) | -x (binary) | ~x (binary) | ~x+1 (binary)
------------+--------------+------------+-------------+-------------+---------------
     5      |      -5      |  0000 0101 |  1111 1011  |  1111 1010  |  1111 1011
    -5      |       5      |  1111 1011 |  0000 0101  |  0000 0100  |  0000 0101
   110      |    -110      |  0110 1110 |  1001 0010  |  1001 0001  |  1001 0010
   -38      |      38      |  1101 1010 |  0010 0110  |  0010 0101  |  0010 0110

Note the -x (binary) column and the ~x+1 (binary) column are the same.

If you need to get the 1's complement of a number, that's just ~x.

于 2013-09-01T20:56:32.110 回答