Abstract
- Integer encoding is the process of representing decimal integers in the form of zeros and ones, supporting both positive and negative integer
- There are 3 integer encoding variants; Sign-and-Magnitude (原码), 1’s Complement (反码) and 2’s Complement (补码), computer uses the 2’s Complement to store integer, because it solves the flaws of Sign-and-Magnitude (原码) and 1’s Complement (反码)
- Below is a 4-bits integer encoding under the 3 variants
Decimal | Signed Magnitude | One’s Complement | Two’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 Decimal | Signed Magnitude | Negative Decimal | Signed 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 (反码)
Decimal | Signed Magnitude | One’s Complement |
---|---|---|
- Basically same as the Sign-and-Magnitude (原码), but for negative decimal integers, all magnitude bits are inverted
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 (补码)
Decimal | One’s Complement | Two’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.