๐๐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
- Divide the decimal number by 2
- Store the remainder (0 or 1)
- Update the number to quotient (number / 2)
- Repeat steps 1-3 until number becomes 0
- Read remainders from bottom to top = binary
๐ข Step-by-Step: Converting 25 to Binary
| Division | Quotient | Remainder |
|---|---|---|
| 25 รท 2 | 12 | 1 |
| 12 รท 2 | 6 | 0 |
| 6 รท 2 | 3 | 0 |
| 3 รท 2 | 1 | 1 |
| 1 รท 2 | 0 | 1 |
Read remainders bottom-up: 11001
Program Code
decimal_binary.c
C
1#include <stdio.h>23int 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 binary17 while (decimal > 0) {18 binary[i] = decimal % 2; // Get remainder (0 or 1)19 decimal /= 2; // Update quotient20 i++;21 }22 23 // Print in reverse order24 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 % 2Gets the remainder when divided by 2 (always 0 or 1). This is the rightmost bit.
decimal /= 2Integer 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
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials