Header Ads Widget

Ticker

6/recent/ticker-posts

Write a C program to perform the following compliment Operations. a)1’s Complement b)2’s Complement

A)1’s Complement

#include <stdio.h>

#define SIZE 8

int main()
{
    char binary[SIZE + 1], onesComp[SIZE + 1];
    int i, error=0;

    printf("Enter %d bit binary value: ", SIZE);
   
    /* Input binary string from user */
    gets(binary);

    /* Store all inverted bits of binary value to onesComp */
    for(i=0; i<SIZE; i++)
    {
        if(binary[i] == '1')
        {
            onesComp[i] = '0';
        }
        else if(binary[i] == '0')
        {
            onesComp[i] = '1';
        }
        else
        {
            printf("Invalid Input");
            error = 1;

            /* Exits from loop */
            break;
        }
    }

    /* Marks the end of onesComp string */
    onesComp[SIZE] = '\0';

    /* Check if there are binary string contains no error */
    if(error == 0)
    {
        printf("Original binary = %s\n", binary);
        printf("Ones complement = %s", onesComp);
    }

    return 0;
}

B)2’s Complement  

#include <stdio.h>  
int main()  
{  
   int n;  // variable declaration  
   printf("Enter the number of bits do you want to enter :");  
   scanf("%d",&n);  
   char binary[n+1];  // binary array declaration;  
   char onescomplement[n+1]; // onescomplement array declaration  
   char twoscomplement[n+1]; // twoscomplement array declaration  
   int carry=1; // variable initialization  
   printf("\nEnter the binary number : ");  
   scanf("%s", binary);  
   printf("%s", binary);  
   printf("\nThe ones complement of the binary number is :");  
     
   // Finding onescomplement in C  
   for(int i=0;i<n;i++)  
   {  
       if(binary[i]=='0')  
       onescomplement[i]='1';  
       else if(binary[i]=='1')  
       onescomplement[i]='0';  
   }  
   onescomplement[n]='\0';  
   printf("%s",onescomplement);  
   
 
printf("\nThe twos complement of a binary number is : ");  
 
// Finding twoscomplement in C  
for(int i=n-1; i>=0; i--)  
    {  
        if(onescomplement[i] == '1' && carry == 1)  
        {  
            twoscomplement[i] = '0';  
        }  
        else if(onescomplement[i] == '0' && carry == 1)  
        {  
            twoscomplement[i] = '1';  
            carry = 0;  
        }  
        else  
        {  
            twoscomplement[i] = onescomplement[i];  
        }  
    }  
twoscomplement[n]='\0';  
printf("%s",twoscomplement);  
return 0;  
}

Post a Comment

0 Comments