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

前端 未结 4 1031
一生所求
一生所求 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:03

    Short answer: If you don't add 1 then you have two different representations of the number 0.

    Longer answer: In one's complement

    • the values from 0000 to 0111 represent the numbers from 0 to 7

    • the values from 1111 to 1000 represent the numbers from 0 to -7

      • since their inverses are 0000 and 0111.

    There is the problem, now you have 2 different ways of writing the same number, both 0000 and 1111 represent 0.

    If you add 1 to these inverses they become 0001 and 1000 and represent the numbers from -1 to -8 therefore you avoid duplicates.

提交回复
热议问题