In this post we will learn how to write a C Program to Convert Decimal Numbers to Binary Numbers.
Example 2
Convert the decimal number 35 to binary.
Solution
Write out the number at the right corner. Divide the number continuously by 2 and write the quotient and the remainder. The quotients move to the left, and the remainder is recorded under each quotient. Stop when the quotient is zero.
0 <- 1 <- 2 <- 4 <- 8 <- 17 <- 35 Dec.
Binary 1 0 0 0 1 1
Convert Decimal to Binary in C
/** C program to convert decimal number into binary by codebind.com */ #include <stdio.h> #include <conio.h> /* Function to convert a decimal number to binary number */ long DecimalToBinary(long n) { int remainder; long binary = 0, i = 1; while(n != 0) { remainder = n%2; n = n/2; binary= binary + (remainder*i); i = i*10; } return binary; } int main() { long decimal; printf("Please Enter a decimal number : "); scanf("%ld", &decimal); printf("Binary number of %ld is %ld\n", decimal, DecimalToBinary(decimal)); getch(); return 0; } /* OUTPUT: Please Enter a decimal number : 7 Binary number of 7 is 111 */
Leave a Reply