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

Required knowledge:

Basic C programming, Bitwise operator, Loop, Array

Program:

/**
 * 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;

    //Converts 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;
    }

    //Prints 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 ;)


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).

2 comments: