Why we need to add 1 while doing 2's complement

前端 未结 4 1021
一生所求
一生所求 2020-12-30 15:06

The 2\'s complement of a number which is represented by N bits is 2^N-number.
For example: if number is 7 (0111) and i\'m representing it using 4 bits then, 2\'s comple

4条回答
  •  一向
    一向 (楼主)
    2020-12-30 16:00

    Your error is in "we do one's compliment and get -7". To see why this is wrong, take the one's complement of 7 and add 7 to it. If it's -7, you should get zero because -7 + 7 = 0. You won't.

    The one's complement of 7 was 1000. Add 7 to that, and you get 1111. Definitely not zero. You need to add one more to it to get zero!

    The negative of a number is the number you need to add to it to get zero.

    If you add 1 to ...11111, you get zero. Thus -1 is represented as all 1 bits.

    If you add a number, say x, to its 1's complement ~x, you get all 1 bits.

    Thus:
    ~x + x = -1

    Add 1 to both sides:
    ~x + x + 1 = 0

    Subtract x from both sides:
    ~x + 1 = -x

提交回复
热议问题