C program to convert decimal to binary number system using bitwise operator

Write a C program to input any decimal number from user and convert it to binary number system using bitwise operator. How to convert from decimal number system to binary number system using bitwise operator in C programming. Logic to convert decimal to binary using bitwise operator in C program.

Example

Input

Input any number: 22

Output

Binary number: 00000000000000000000000000010110

Required knowledge

Bitwise operators, Data types, Basic input/output, While loop, Array

Learn program to - convert decimal to binary without using bitwise operator.

Logic to convert decimal to binary using bitwise operator

Step by step descriptive logic to convert decimal to binary number system.

  1. Input a decimal number from user. Store it in some variable say num.
  2. Declare an array of size required to store an integer in memory (i.e. 32 bits), say bin[INT_SIZE];.
  3. Initialize another variable to store index, say index = INT_SIZE - 1;.
  4. Run a loop from INT_SIZE to 0. Inside the loop assign Least Significant Bit to bin[index]. Perform bin[index] = num & 1;.
  5. Decrement index by 1 and right shift num by 1.

Program to convert decimal to binary using bitwise operator

/**
 * C program to convert decimal to binary number system
 */

#include <stdio.h>
#define INT_SIZE sizeof(int) * 8 /* Size of int in bits */

int main()
{
    int num, index, i;
    int bin[INT_SIZE];

    /* Input number from user */
    printf("Enter any number: ");
    scanf("%d", &num);

    index = INT_SIZE - 1;

    while(index >= 0)
    {
        /* Store LSB of num to bin */
        bin[index] = num & 1;

        /* Decrement index */
        index--;

        /* Right Shift num by 1 */
        num >>= 1;
    }

    /* Print converted binary */
    printf("Converted binary: ");
    for(i=0; i<INT_SIZE; i++)
    {
        printf("%d", bin[i]);
    }

    return 0;
}

Output

Enter any number: 22
Converted binary : 00000000000000000000000000010110

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>