Sai A
Updated date Feb 27, 2024
In this blog, we will learn how to convert decimal numbers to binary in C programming. Explore multiple methods, including division and remainder, bitwise operators, with clear explanations, code examples, and outputs.

## Introduction:

Binary numbers, composed of only two digits (0 and 1), are fundamental in computer science and digital electronics. Understanding how to convert decimal numbers to binary is essential for programmers, as it forms the basis of many operations in computing. In this blog, we will explore various methods to perform decimal to binary conversion using the C programming language.

## Method 1: Using Division and Remainder

To convert a decimal number to binary is by repeatedly dividing the decimal number by 2 and noting the remainder. Let's illustrate this method with an example:

Consider the decimal number 13.

1. Divide 13 by 2: Quotient = 6, Remainder = 1
2. Divide 6 by 2: Quotient = 3, Remainder = 0
3. Divide 3 by 2: Quotient = 1, Remainder = 1
4. Divide 1 by 2: Quotient = 0, Remainder = 1

Now, we read the remainder from bottom to top: 1101. This is the binary representation of 13.

Let's see how this is implemented in C:

``````#include <stdio.h>

void decimalToBinary(int n) {
// Base case
if (n == 0)
return;

decimalToBinary(n / 2);
printf("%d", n % 2);
}

int main() {
int decimal = 13;
printf("Binary representation of %d: ", decimal);
decimalToBinary(decimal);
printf("\n");
return 0;
}
``````

### Output:

``````Binary representation of 13: 1101
``````

## Method 2: Using Bitwise Operators

Another approach to convert decimal to binary involves bitwise operators in C. This method is efficient and straightforward, using bitwise AND operations to extract the binary digits.

Let's see how this is implemented:

``````#include <stdio.h>

void decimalToBinary(int n) {
int i;
for (i = 31; i >= 0; i--) {
int k = n >> i;
if (k & 1)
printf("1");
else
printf("0");
}
}

int main() {
int decimal = 13;
printf("Binary representation of %d: ", decimal);
decimalToBinary(decimal);
printf("\n");
return 0;
}
``````

### Output:

``````Binary representation of 13: 00000000000000000000000000001101
``````

## Conclusion:

In this blog, we've looked at different ways to change decimal numbers to binary in C programming. Each way has its good points and teaches us something about how binary works. Whether you like dividing numbers or using special symbols for binary, programmers need to know these methods if they want to work with binary.