Why Two’s Complement ?
- Two’s complement simplifies hardware addition, subtraction and multiplication
- No division can be performed with Two’s complement
Rules :
- Positive number and zero are represented as themselfs in Two’s complement
- Negative number are represented as
- Invert every bit of the negative numbers positive equivalent.
- And the add one to that number
Example :
- We need to represent number -3 in Two’s Complement
- Positive equivalent of -3 is 3
- We convert 3 in bits i.e 00011
- We flip everybit = 11100
- We add 1 to 11100
- The result is 11101
- 11101 is the representation of negative 3 in two’s complement
Two’s Complement in Java
- Remember that negative numbers are stored as the two’s complement of the positive counterpart.
- Let us calculate the 4 complement in java ~4
- 4 is an Integer value
- Integer is of 4 bytes i.e 32 bits
- Most significant bit is signed bit
- If input is positive then 0
- If input is negative then 1
- Since on our case 4 is positive number hence the most significant bit is 0
- Then we need to represent 4 in a 32 bit format which is 00000000 00000000 00000000 00000100
- Combining signed bit and the 32 bit as 0 00000000 00000000 00000000 00000100
- Complementing the data i.e 1 11111111 11111111 11111111 11111011
- Now the leading signed bit is 1 which indicates the result is negative hence the result has to be represented in Two’s complement
- Calculating Two’s complement for the data 1 11111111 11111111 11111111 11111011
- We will not include the signed bit here in this calculation
- First we need to calculate the 1’s complement
- The answer is 1 00000000 00000000 00000000 00000100
- Now add 1 to the above data
- 00000000 00000000 00000000 00000100 + 1
- Result after adding 00000000 00000000 00000000 00000101 which is -5 in decimal
Reference: