Convert a Decimal Number to Binary in C

Let’s understand how to Convert a Decimal Number to Binary in C Programming Language.

C Program to Convert a Decimal Number to Binary

#include <stdio.h>
/*Learn C Programming at CodeAtGlance.com*/
 void main()
{
   long num, dec, rem, temp = 1, binary = 0, count = 0;
    printf("Enter a decimal integer \n");
    scanf("%ld", &num);
    dec = num;
    while (num > 0)
    {
        rem = num % 2;
        if (rem == 1)
        {
            count++;
        }
        binary = binary + rem * temp;
        num = num / 2;
        temp = temp * 10;
    }
    printf("Input number is = %d\n", dec);
    printf("Its binary equivalent is = %ld\n", binary);
    printf("No.of 1's in the binary number is = %d\n", count);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart