What is “2's Complement”?

前端 未结 23 2491
名媛妹妹
名媛妹妹 2020-11-21 05:59

I\'m in a computer systems course and have been struggling, in part, with Two\'s Complement. I want to understand it but everything I\'ve read hasn\'t brought the p

23条回答
  •  日久生厌
    2020-11-21 06:32

    Many of the answers so far nicely explain why two's complement is used to represent negative number, but do not tell us what two's complement number is, particularly not why a '1' is added, and in fact often added in a wrong way.

    The confusion comes from a poor understanding of the definition of a complement number. A complement is the missing part that would make something complete.

    The radix complement of an n digit number x in radix b is, by definition, b^n-x. In binary 4 is represent by 100, which has 3 digits (n=3) and a radix of 2 (b=2). So its radix complement is b^n-x = 2^3-4=8-4=4 (or 100 in binary).

    However, in binary obtaining a radix's complement is not as easy as getting its diminished radix complement, which is defined as (b^n-1)-y, just 1 less than that of radix complement. To get a diminished radix complement, you simply flip all the digits.

    100 -> 011 (diminished (one's) radix complement)

    to obtain the radix (two's) complement, we simply add 1, as the definition defined.

    011 +1 ->100 (two's complement).

    Now with this new understanding, let's take a look of the example given by Vincent Ramdhanie (see above second response)

    /* start of Vincent

    Converting 1111 to decimal:

    The number starts with 1, so it's negative, so we find the complement of 1111, which is 0000. Add 1 to 0000, and we obtain 0001. Convert 0001 to decimal, which is 1. Apply the sign = -1. Tada!

    end of Vincent */

    Should be understood as

    The number starts with 1, so it's negative. So we know it is a two's complement of some value x. To find the x represented by its two's complement, we first need find its 1's complement.

    two's complement of x: 1111 one's complement of x: 1111-1 ->1110; x = 0001, (flip all digits)

    apply the sign -, and the answer =-x =-1.

提交回复
热议问题