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. Finding binary of a decimal number using C program.

Example

Input

Input any number: 22

Output

Binary number: 00000000000000000000000000010110 (in 4 byte integer representation)

Required knowledge

Basic C programming, Bitwise operator, Loop, Array

Read more - Program to convert decimal to binary without using bitwise operator

Program to convert decimal to binary

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

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

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

    printf("Enter any number: ");
    scanf("%d", &num);

    index = INT_SIZE;

    // Convert decimal to binary
    while(index!=0)
    {
        index--;

        // Store 1 if LSB is set otherwise 0
        bin[index] = num & 1;

        // Shift bits of num to one position right
        num >>= 1;
    }

    // Print the converted binary
    printf("Converted binary (in %d byte integer representation): ", sizeof(int));
    for(i=0; i<INT_SIZE; i++)
    {
        printf("%d", bin[i]);
    }

    return 0;
}

Output

Enter any number: 22
Converted binary (in 4 byte integer representation): 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>