Find one's complement of a binary number with C.
/*
Ones complement of a binary number is defined as value obtained by inverting all binary bits. It is the result of swapping all
1s to 0s and all 0s to 1s.
Ones complement of binary value
https://prnt.sc/yLcygN5Nzg84
Print 0 for each 1 binary bit i.e. if(binary[i] == '1').
Print 1 for each 0 binary bit i.e. if(binary[i] == '0').
*/
#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);
gets(binary);
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;
break;
}
}
onesComp[SIZE] = '\0';
if (error == 0)
{
printf("Original binary = %s\n", binary);
printf("Ones complement = %s", onesComp);
}
return 0;
}
Output:-
Enter 8 bit binary value : 11011011
Original binary = 11011011
0 Comments