Abstract


DecimalSigned MagnitudeOne’s ComplementTwo’s Complement
--

Important

For the three integer encoding variants, the encodings for positive integer are exactly the same.

Sign Bit

  • denotes positive
  • denotes negative
  • Usually the first bit from left, the most significant bit (MSB)

Magnitude Bit

  • Represent the magnitude (absolute value) of the integer in standard binary representation

Sign-and-Magnitude (原码)


Positive DecimalSigned MagnitudeNegative DecimalSigned Magnitude
  • Sign-and-magnitude is a method for representing both positive and negative integers using a Sign Bit and magnitude bits. The most significant bit (MSB) is reserved as the sign bit

Unable to performance subtraction with Adder

The Adder is unable to perform subtraction on sign-and-magnitude encoded integers, an explicit set of Logic Gates for substation is needed. This can be avoided using 1’s Complement (反码) or 2’s Complement (补码).

1’s Complement (反码)


DecimalSigned MagnitudeOne’s Complement

Reuse adder for subtraction

We can reuse Adder Logic Gates to perform subtraction without the need for dedicated subtraction logic gates.

Mathematically wrong definition of 0

We have +0 (when all bits are 0) & -0(when all bits are 1) under this encoding, this can be solved with 2’s Complement (补码).

2’s Complement (补码)


DecimalOne’s ComplementTwo’s Complement
-
  • This builds on top of 1’s Complement (反码), the only difference being to add to the 1’s complement (反码) integer encoding for negative numbers

Mathematically correct definition of Zero

The integer encoding for both and is , thus eliminating two different integer encodings for .

Trick to convert from 2's complement to decimal value

The decimal value = the negative decimal value of Sign Bit + the positive sum of the magnitude bits.

Integer Overflow


  • When a value is out of the range that the Datatype can hold

Check for Integer Overflow

If the Sign Bit of the two operand is the same, and the sign bit of the result is different. Then we have an Integer (整数) overflow.

How can the sum of two positive integer result in a negative number, and how the sum of two negative integer result in a positive number?

The sum of a negative and positive integer guaranteed no integer overflow.

Reference