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

  1. Start with the binary representation of the positive number.
  2. Invert all the bits (flip 0 to 1 and 1 to 0).
  3. 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:

00000101

To find the 2's complement of -5:

  1. Start with the binary representation of 5: 00000101
  2. Invert the bits: 11111010
  3. 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

2's complement of 5 is: -5

Advantages of 2's Complement

Disadvantages of 2's Complement