Reputation: 2642
The way to find Two's Complement of a binary number is:
- Let x ̄ = the logical complement of x. The logical complement (also called the one’s complement) is formed by flipping all the bits in the number, changing all of the 1 bits to 0, and vice versa.
- Let X = x ̄ + 1. If this addition overflows, then the overflow bit is discarded. By the definition of two’s complement, X ≡ −x.
I have seen a quick way, which is:
eg.
B = 00010110 D = 22
Flip everything after the first "1" counting from left side.
-B = 11101010 -D = -22
I couldn't understand proof of this way.
Upvotes: 3
Views: 2132
Reputation:
Two's complement on Wikipedia
A shortcut to manually convert a binary number into its two's complement is to start at the least significant bit (LSB), and copy all the zeros, working from LSB toward the most significant bit (MSB) until the first 1 is reached; then copy that 1, and flip all the remaining bits (Leave the MSB as a 1 if the initial number was in sign-and-magnitude representation). This shortcut allows a person to convert a number to its two's complement without first forming its ones' complement. For example: in two's complement representation, the negation of "0011 1100" is "1100 0100", where the underlined [bolded] digits were unchanged by the copying operation (while the rest of the digits were flipped).
So I guess what you said "Flip everything after the first "1" counting from left side." needs to be fixed as "Flip everything after the first "1" counting from RIGHT side."
Here is the "slow way": 22 decimal = 00010110 binary -> flip: 11101001 -> plus 1: 11101001 + 1 = 11101010 = -22 decimal
Upvotes: 4
Reputation: 64904
If you take the definition, -x = ~x + 1
, then if we represent x
as a string a10k (a string a
followed by a 1 followed by k zeros), then:
-(a10^k) =
// by definition
~(a10^k) + 1 =
// complement distributes over concatenation
~a01^k + 1 =
// carry through the 1s and set the 0
~a10^k
The final result, ~a10^k
, means "complement the left side, until (and not including) the rightmost 1".
This proof did not hold for x = 0
since it cannot be written in the form a10k, the equivalence is still true: there is no part to complement since there is no rightmost 1, so the result is zero again which is correct.
Upvotes: 4