C Program to find two’s complement for a given number

CServer Side ProgrammingProgramming

The two’s complement for a given binary number can be calculated in two methods, which are as follows −

  • Method 1 − Convert the given binary number into one’s complement and then, add 1.

  • Method 2 − The trailing zero’s after the first bit set from the Least Significant Bit (LSB) including one that remains unchanged and remaining all should be complementing.

The logic to find two’s complement for a given binary number is as follows −

for(i = SIZE - 1; i >= 0; i--){
   if(one[i] == '1' && carry == 1){
      two[i] = '0';
   }
   else if(one[i] == '0' && carry == 1){
      two[i] = '1';
      carry = 0;
   } else {
      two[i] = one[i];
   }
}
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s\n",num, two);

The logic for finding one’s complement from a given binary number is −

for(i = 0; i < SIZE; i++){
   if(num[i] == '0'){
      one[i] = '1';
   }
   else if(num[i] == '1'){
      one[i] = '0';
   }
}
one[SIZE] = '\0';
printf("Ones' complement of binary number %s is %s\n",num, one);

Example

Following is the C program to find two’s complement for a given number −

 Live Demo

#include<stdio.h>
#include<stdlib.h>
#define SIZE 8
int main(){
   int i, carry = 1;
   char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
   printf("Enter the binary number\n");
   gets(num);
   for(i = 0; i < SIZE; i++){
      if(num[i] == '0'){
         one[i] = '1';
      }
      else if(num[i] == '1'){
         one[i] = '0';
      }
   }
   one[SIZE] = '\0';
   printf("Ones' complement of binary number %s is %s\n",num, one);
   for(i = SIZE - 1; i >= 0; i--){
      if(one[i] == '1' && carry == 1){
         two[i] = '0';
      }
      else if(one[i] == '0' && carry == 1){
         two[i] = '1';
         carry = 0;
      }
      else{
         two[i] = one[i];
      }
   }
   two[SIZE] = '\0';
   printf("Two's complement of binary number %s is %s\n",num, two);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Enter the binary number
1000010
Ones' complement of binary number 1000010 is 0111101
Two's complement of binary number 1000010 is 0111110
raja
Published on 12-Mar-2021 06:50:19
Advertisements