Write a C program to read binary number from user and find two's complement of the binary number. How to find 2's complement of a binary number in C.

Input binary number: 0110 1110

Output 2's complement : 1001 0010

Or in simple words two's complement can be also defined as sum of 1's complement of the binary number and 1.

Happy coding ;)

**Example:**Input binary number: 0110 1110

Output 2's complement : 1001 0010

### Required knowledge:

Basic C programming, For loop, String#### Two's complement

Wikipedia states that the two's complement of an*N*-bit number is defined as the complement with respect to 2^{N}; in other words, it is the result of subtracting the number from 2^{N}, which in binary is one followed by*N*zeroes.Or in simple words two's complement can be also defined as sum of 1's complement of the binary number and 1.

### Program:

/** * C program to find 2's complement of a binary number */ #include <stdio.h> #include <string.h> #define SIZE 8 int main() { char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE + 1]; int i, carry=1; /* * Reads binary number from user */ printf("Enter any %d bit binary value: ", SIZE); gets(binary); /* * Finds the 1's complement of the binary number */ for(i=0; i<SIZE; i++) { if(binary[i]=='1') { onesComp[i] = '0'; } else if(binary[i]=='0') { onesComp[i] = '1'; } } onesComp[SIZE] = '\0'; /* * Adds 1 to the 1's complement of the binary number to get 2's complement */ for(i=SIZE-1; i>=0; i--) { if(onesComp[i]=='1' && carry==1) { twosComp[i] = '0'; } else if(onesComp[i]=='0' && carry==1) { twosComp[i] = '1'; carry = 0; } else { twosComp[i] = onesComp[i]; } } twosComp[SIZE] = '\0'; printf("\nOriginal binary value = %s\n", binary); printf("One's complement = %s\n", onesComp); printf("Two's complement = %s", twosComp); return 0; }

Output

Enter any 8 bit binary value: 01101100

Original binary value = 01101100

One's complement = 10010011

Two's complement = 10010100

Original binary value = 01101100

One's complement = 10010011

Two's complement = 10010100

Happy coding ;)

### You may also like

- Loop programming exercises and solutions in C.
- C program to find one's complement of a binary number.
- C program to convert Binary to Octal number system.
- C program to convert Binary to Decimal number system.
- C program to convert Binary to Hexadecimal number system.
- C program to convert Octal to Binary number system.
- C program to convert Octal to Decimal number system.
- C program to convert Octal to Hexadecimal number system.
- C program to convert Decimal to Binary number system.
- C program to convert Decimal to Octal number system.
- C program to convert Decimal to Hexadecimal number system.
- C program to convert Hexadecimal to Binary number system.
- C program to convert Hexadecimal to Octal number system.
- C program to convert Hexadecimal to Decimal number system.

< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).