C program to find ones complement of a binary number

Previous Program Next Program

Write a C program to read binary number from user and find one's complement of binary number using loop. How to find 1's complement of a binary number in C programming. Logic to find ones complement of binary number in C program.

Example

Input

Input binary number: 01000011

Output

Ones complement: 10111100

Required knowledge

Basic C programming, If else, For loop, String

What is Ones complement?

Ones complement of a binary number is defined as value obtained by inverting all binary bits. It is the result of swapping all 1's to 0's and all 0's to 1's.

Ones complement of a binary number
Read more about Ones complement

Logic to find ones complement

Below is the step by step logic to find ones complement of binary number.

  1. Read a binary string from user. Store it in some variable say binary.
  2. Run a loop from 1 to length of binary string, incrementing 1 in each iteration. The loop structure should look like for(i=0; i<SIZE; i++) (where SIZE is the length of binary digit).
  3. Inside the loop there can be two cases -
    Case I: Print 0 for each 1 binary bit i.e. if binary[i] == '1' then, print 0.
    Case II: Print 1 for each 0 binary bit i.e. if binary[i] == '0' then, print 1.

Program to find ones complement

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

#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);
    
    // Read binary string from user
    gets(binary);

    /*
     * Store all inverted bits of binary value to onesComp
     */
    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;

            // Exits from loop
            break;
        }
    }
    // Marks the end of onesComp string
    onesComp[SIZE] = '\0';

    if(error == 0)
    {
        printf("Original binary = %s\n", binary);
        printf("Ones complement = %s", onesComp);
    }

    return 0;
} 
Output
Enter any 8 bit binary value: 00001111
Original binary = 00001111
Ones complement = 11110000

Happy coding ;)

Recommended posts

Previous Program Next Program
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
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment