In this article, we are going to learn how to find the One’s Complement of a Binary number entered by the user. A binary number consists of 0s and 1s in its composition. We can get the One’s Complement of a Binary number by just inverting the 0s to 1s and 1s to 0s. It is just swapping the bits.
C program to find One’s complement of a binary number
In this C program input binary number from user and find one complement of a binary number using for loop. We are going to take input from the user as a binary number and then we will iterate over this number one bit at a time.
With each iteration, we will check if the bit is 1 or 0. Then by using the if-else statement we will invert the 1 to 0 and 0 to 1. This will give us the 1s complement when we will reach the end of iterations. This is how to 1s complement a binary number in C programming.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char binNum[8 + 1], binComp[8 + 1];
printf("Please enter 8 bit binary number : ");
scanf("%s",binNum);
for(int i = 0; i < 8; i++)
{
if(binNum[i] == '1')
{
binComp[i] = '0';
}
else if(binNum[i] == '0')
{
binComp[i] = '1';
}
else
{
printf("You entered a Non-Binary Number.Exiting Program");
exit(0);
}
}
binComp[8] = '
#include <stdio.h>
#include <stdlib.h>
int main()
{
char binNum[8 + 1], binComp[8 + 1];
printf("Please enter 8 bit binary number : ");
scanf("%s",binNum);
for(int i = 0; i < 8; i++)
{
if(binNum[i] == '1')
{
binComp[i] = '0';
}
else if(binNum[i] == '0')
{
binComp[i] = '1';
}
else
{
printf("You entered a Non-Binary Number.Exiting Program");
exit(0);
}
}
binComp[8] = '\0';
printf("Ones complement of %s is %s",binNum, binComp);
return 0;
}
';
printf("Ones complement of %s is %s",binNum, binComp);
return 0;
}
Output
Please enter 8 bit binary number : 10101010
Ones complement of 10101010 is 01010101
Please enter 8 bit binary number : 12098096
You entered a Non-Binary Number.Exiting Program