Contents
What is 2’s Complement?
The 2’s complement in C is formed by the 1’s complement in C. We know that the 1’s complement of a binary number is formed by changing 1 to 0 and 0 to 1; The 2’s complement of a binary number is formed by adding the 1’s complement of a binary number.
In short, we can say that the sum of the 2’s in C is defined as the sum of the 1’s and the 1’s in C.
In the above figure, the binary number is equal to 00000101 and its sum is calculated by changing 1 to 0 and 0 to 1. So an addition would be 11111010. We add another 1 to one to calculate the sum. two more and the result is 11111011.
Example
#include <stdio.h>
int main() {
int decimalNum, twosComp;
// Input decimal number
printf(“Enter a decimal number: “);
scanf(“%d”, &decimalNum);
// Calculate 2’s complement
twosComp = ~decimalNum + 1; // Bitwise NOT and add 1
// Display decimal number and its 2’s complement
printf(“Decimal: %d\n”, decimalNum);
printf(“2’s Complement: %d\n”, twosComp);
return 0;
}
Output
Enter a decimal number: 10
Decimal: 10
2’s Complement: -10
Advantages and Disadvantages
-
Advantages
-
Efficient Arithmetic Operations:
Addition, subtraction, and multiplication can be accomplished directly by adding 2 using the same electronics designed for unsigned numbers. This makes it easy to do the math from both a hardware and software perspective.
-
Single Representation for Zero:
Unlike sign and addition representations of two, which have separate representations for positive and negative zero, the sum of 2 has one representation for zero, making arithmetic easier.
-
Straightforward Overflow Handling:
Overflow conditions in 2’s complement arithmetic can be easily detected and handled by discarding the overflow, ensuring inconsistent handling of arithmetic operations.
-
Symmetric Range:
The range of numbers represented by 2’s complement is symmetrical with respect to zero; This means that the same number of components can represent the same number of positive and negative numbers.
Disadvantages
-
Complexity of Negation:
Negating a number in 2’s complement requires adding a bit (NOT) to the number and then adding This extra step adds complexity compared to other representations such as signed more and less.
-
One Extra Negative Value:
In addition to 2, a negative result is obtained instead of a positive result due to the asymmetric range around zero. This can cause problems when representing the least negative.
-
Difficulty in Mental Arithmetic:
Mental arithmetic using 2’s complement can be more difficult than other notations, especially when dealing with negative numbers and past events.
-
Limited Range:
Like all representation generals, 2’s complement has a finite number of digits determined by multiplication. Apart from this, this may cause crashes and crashes while working on the code.