Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Decimal to Binary conversion using C Programming
Decimal to binary conversion is a fundamental concept in computer programming. In C, we can convert decimal numbers to their binary representation using simple mathematical operations and functions.
Syntax
long decimalToBinary(int decimal_number);
Method 1: Using Function with Mathematical Approach
This method uses modulo and division operations to extract binary digits and build the binary number −
#include <stdio.h>
long decimalToBinary(int dno) {
long bno = 0, rem, f = 1;
while (dno != 0) {
rem = dno % 2;
bno = bno + rem * f;
f = f * 10;
dno = dno / 2;
}
return bno;
}
int main() {
int dno;
long bno;
printf("Enter any decimal number: ");
scanf("%d", &dno);
bno = decimalToBinary(dno);
printf("The Binary value is: %ld<br>", bno);
return 0;
}
Enter any decimal number: 12 The Binary value is: 1100
Method 2: Using Array to Store Binary Digits
This approach stores binary digits in an array and prints them in reverse order −
#include <stdio.h>
void decimalToBinaryArray(int dno) {
int binary[32];
int i = 0;
if (dno == 0) {
printf("Binary: 0<br>");
return;
}
while (dno > 0) {
binary[i] = dno % 2;
dno = dno / 2;
i++;
}
printf("Binary: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d", binary[j]);
}
printf("<br>");
}
int main() {
int dno;
printf("Enter a decimal number: ");
scanf("%d", &dno);
decimalToBinaryArray(dno);
return 0;
}
Enter a decimal number: 25 Binary: 11001
Binary to Decimal Conversion
Here's the reverse conversion from binary to decimal using the power function −
#include <stdio.h>
#include <math.h>
int binaryToDecimal(long bno) {
int dno = 0, i = 0, rem;
while (bno != 0) {
rem = bno % 10;
bno /= 10;
dno += rem * pow(2, i);
++i;
}
return dno;
}
int main() {
long bno;
int dno;
printf("Enter a binary number: ");
scanf("%ld", &bno);
dno = binaryToDecimal(bno);
printf("The decimal value is: %d<br>", dno);
return 0;
}
Enter a binary number: 10011 The decimal value is: 19
How It Works
- Decimal to Binary: Divide the number by 2 repeatedly and collect remainders in reverse order.
- Binary to Decimal: Multiply each binary digit by powers of 2 and sum them up.
- The mathematical approach builds the binary number as a long integer.
- The array method is more flexible for larger binary numbers.
Conclusion
Decimal to binary conversion in C can be implemented using mathematical operations or arrays. Both methods effectively demonstrate the relationship between decimal and binary number systems in programming.
Advertisements
