2's Complement in C
In C programming, 2's complement is a mathematical representation used to represent negative numbers in binary. It is one of the most common methods for encoding signed numbers, and it allows for simple arithmetic operations such as addition and subtraction on both positive and negative numbers.
Understanding 2's Complement
2's complement works by inverting the bits of a number and adding 1 to the least significant bit (LSB). The method is mainly used for simplifying binary arithmetic and ensuring that both positive and negative numbers can be represented with the same binary system.
Steps to Find 2's Complement
- Start with the binary representation of the positive number.
- Invert all the bits (flip 0 to 1 and 1 to 0).
- Add 1 to the inverted binary number.
Example: Finding 2's Complement of a Number
Let's take the number 5 as an example. The binary representation of 5 in 8-bit form is:
00000101To find the 2's complement of -5:
- Start with the binary representation of 5:
00000101
- Invert the bits:
11111010
- Add 1:
11111010 + 1 = 11111011
Thus, the 2's complement of -5 is 11111011
in an 8-bit system.
Example Code to Show 2's Complement in C
Here’s a C program that demonstrates how the 2's complement of a number is calculated:
Example
#include <stdio.h>
int main()
{
int num = 5;
int complement = ~num + 1; // 2's complement: invert bits and add 1
printf("2's complement of %d is: %d\n", num, complement);
return 0;
}
Output
Advantages of 2's Complement
- Simplified Arithmetic: 2's complement simplifies the implementation of arithmetic operations, especially addition and subtraction, since both positive and negative numbers can be handled uniformly.
- Efficient Representation: It allows for efficient representation of negative numbers in binary form and supports direct arithmetic operations without requiring separate logic for positive and negative values.
- Easy to Convert: Converting a number from positive to negative (or vice versa) using 2's complement is straightforward.
Disadvantages of 2's Complement
- Limited Range: In a system with a fixed number of bits, the range of representable values is limited. For example, in an 8-bit system, the range is -128 to 127.
- Overflow: 2's complement can lead to overflow if the result exceeds the maximum or minimum representable values for a given bit width.