The 2s complement in C is generated from the 1s complement in C. As we know that the 1s complement of a binary number is created by transforming bit 1 to 0 and 0 to 1; the 2s complement of a binary number is generated by adding one to the 1s complement of a binary number.
In short, we can say that the 2s complement in C is defined as the sum of the one's complement in C and one.
In the above figure, the binary number is equal to 00010100, and its one's complement is calculated by transforming the bit 1 to 0 and 0 to 1 vice versa. Therefore, one's complement becomes 11101011. After calculating one's complement, we calculate the two's complement by adding 1 to the one's complement, and its result is 11101100.
Let's create a program of 2s 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; }
Output