๐Ÿ”„๐Ÿ“šIntermediate

Decimal to Binary Conversion

Convert decimal to binary

Convert decimal to binary by repeatedly dividing by 2 and collecting remainders. The binary number system uses only 0 and 1 (base 2).

๐Ÿ“ Algorithm

  1. Divide the decimal number by 2
  2. Store the remainder (0 or 1)
  3. Update the number to quotient (number / 2)
  4. Repeat steps 1-3 until number becomes 0
  5. Read remainders from bottom to top = binary

๐Ÿ”ข Step-by-Step: Converting 25 to Binary

DivisionQuotientRemainder
25 รท 2121
12 รท 260
6 รท 230
3 รท 211
1 รท 201

Read remainders bottom-up: 11001

Program Code

decimal_binary.c
C
1#include <stdio.h>
2
3int main() {
4 int decimal, binary[32], i = 0;
5
6 printf("Enter a decimal number: ");
7 scanf("%d", &decimal);
8
9 int original = decimal;
10
11 if (decimal == 0) {
12 printf("Binary: 0\n");
13 return 0;
14 }
15
16 // Convert to binary
17 while (decimal > 0) {
18 binary[i] = decimal % 2; // Get remainder (0 or 1)
19 decimal /= 2; // Update quotient
20 i++;
21 }
22
23 // Print in reverse order
24 printf("Binary of %d: ", original);
25 for (int j = i - 1; j >= 0; j--) {
26 printf("%d", binary[j]);
27 }
28 printf("\n");
29
30 return 0;
31}
Output

Enter a decimal number: 25

Binary of 25: 11001

Code Explanation

binary[i] = decimal % 2

Gets the remainder when divided by 2 (always 0 or 1). This is the rightmost bit.

decimal /= 2

Integer division by 2. Removes the rightmost bit we just extracted.

for (j = i - 1; j >= 0; j--)

Print in reverse order because we collected LSB (least significant bit) first.

๐ŸŽฏ Key Takeaways

โœ“Use % 2 to get binary digit
โœ“Use / 2 to shift right
โœ“Print in reverse order
โœ“Handle zero as special case

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples