Program for Decimal to Binary Conversion in C

Decimal to Binary Conversion

Converting a decimal number to binary involves representing the number in base-2, where each digit is either 0 or 1.

We will explore three methods to perform this conversion using C programming.

Method 1: Using Bitwise Operators

We use bitwise operations to extract each bit from the number.

#include <stdio.h>

void decimalToBinary_bitwise(int n) {
    for (int i = 31; i >= 0; i--) {
        printf("%d", (n >> i) & 1);
    }
    printf("\n");
}

int main() {
    int num;
    printf("Enter a decimal number: ");
    scanf("%d", &num);
    decimalToBinary_bitwise(num);
    return 0;
}
            

Method 2: Using Division by 2

We repeatedly divide the number by 2 and store the remainder.

#include <stdio.h>

void decimalToBinary_division(int n) {
    int binary[32], i = 0;
    while (n > 0) {
        binary[i++] = n % 2;
        n /= 2;
    }
    for (int j = i - 1; j >= 0; j--) {
        printf("%d", binary[j]);
    }
    printf("\n");
}

int main() {
    int num;
    printf("Enter a decimal number: ");
    scanf("%d", &num);
    decimalToBinary_division(num);
    return 0;
}
            

Method 3: Using Recursion

We use recursion to keep dividing the number by 2 until it becomes 0, printing the remainder in reverse order.

#include <stdio.h>

void decimalToBinary_recursive(int n) {
    if (n == 0)
        return;
    decimalToBinary_recursive(n / 2);
    printf("%d", n % 2);
}

int main() {
    int num;
    printf("Enter a decimal number: ");
    scanf("%d", &num);
    if (num == 0)
        printf("0");
    else
        decimalToBinary_recursive(num);
    printf("\n");
    return 0;
}
            
Numbers

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

HCF - Highest Common Factor: C C++ Java Python

LCM - Lowest Common Multiple: C C++ Java Python

GCD - Greatest Common Divisor: C C++ Java Python

Binary to Decimal Conversion: C C++ Java Python

Octal to Decimal Conversion: C C++ Java Python

Hexadecimal to Decimal Conversion: C C++ Java Python

Decimal to Binary Conversion: C C++ Java Python

Decimal to Octal Conversion: C C++ Java Python

Decimal to Hexadecimal Conversion: C C++ Java Python

Binary to Octal Conversion: C C++ Java Python

Quadrants in which a given coordinate lies: C C++ Java Python

Addition of Two Fractions: C C++ Java Python

Calculate the Area of a Circle: C C++ Java Python

Convert Digit/Number to Words: C C++ Java Python

Finding Roots of a Quadratic Equation: C C++ Java Python