C program to find ones complement of a binary number

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

Input binary number: 01000011
Ones's complement: 10111100

Required knowledge:

Basic C programming, For loop, String

One's complement

One's complement of a binary number is defined as value obtained by inverting all binary bits i.e. swapping all 1's to 0's and all 0's to 1's.
1's complement of a binary number


 * C program to find 1's complement of a binary number

#include <stdio.h>
#include <string.h>

#define SIZE 8

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

     * Reads binary value from user
    printf("Enter any %d bit binary value: ", SIZE);

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

        printf("\nOriginal binary = %s\n", binary);
        printf("Ones complement = %s", onesComp);

    return 0;
Enter any 8 bit binary value: 00001111

Original binary = 00001111
Ones complement = 11110000

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment