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

前端 未结 4 1033
一生所求
一生所求 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 15:52

    The +1 is added so that the carry over in the technique is taken care of.

    Take the 7 and -7 example.

    If you represent 7 as 00000111

    In order to find -7:

    Invert all bits and add one

    11111000 -> 11111001

    Now you can add following standard math rules:

      00000111
    + 11111001
     -----------
      00000000
    

    For the computer this operation is relatively easy, as it involves basically comparing bit by bit and carrying one.

    If instead you represented -7 as 10000111, this won't make sense:

       00000111
    +  10000111
      -----------
       10001110 (-14)
    

    To add them, you will involve more complex rules like analyzing the first bit, and transforming the values.

    A more detailed explanation can be found here.

提交回复
热议问题