How To Convert Decimal To Binary In C

A fundamental operation in computer programming, particularly in systems programming and computer architecture, is converting a decimal integer to binary. This translation can be carried out in C programming by implementing a loop to carry out the required computations and print out the binary equivalent.

Any decimal number can be converted to binary, a base-2 numeral system that only utilises the digits 0 and 1 to represent all numbers, by following a few simple steps.

This tutorial will learn how to convert decimal to binary in C programming.

Why there is need to convert decimal to binary

Need to convert decimal to binary is for performing bitwise operations on data. In C, bitwise operators work on the binary representation of data, so converting decimal numbers to binary allows you to perform these operations.

Here are some reasons why is it necessary to convert decimal to binary in c language:

  1. It is essential to convert decimal to binary in C programming for a number of reasons. The fact that computers store and analyse data in binary is one of the most different topics. Because the binary system simply requires the digits 0 and 1, computers can store and modify data with ease. Hence, programming and a comprehension of how computers function require the ability to convert among decimal and binary.
  2. Another argument for doing so is because doing so is a necessary step in using bitwise operators. Working with bitwise operators, typically change a number’s bits one at a time, requires an understanding how to convert between binary and decimal. In low-level programming tasks like device drivers, networking protocols, and operating systems, bitwise operators are utilised generally.
  3. Additionally, converting decimal to binary is often necessary when working with embedded systems, which are used in a wide range of applications, including robotics, automotive systems, and medical devices. These systems often use binary representations of data to save memory and processing power.
  4. Overall, knowing how to convert decimal to binary is an important skill for anyone working in the field of computer programming. It is a fundamental operation that is essential for working with bitwise operators and embedded systems, as well as for understanding how computers store and process data.

Different approaches to convert decimal to binary

These are the five approaches which solve the problem of how to convert decimal to binary in c.

  1. Using bitwise operators
  2. Using division and modulo operators
  3. Using recursive function
  4. Using lookup tables
  5. Using library functions

Detailed Explanation

1. Using bitwise operators:

Converting decimal to binary using bitwise operators is a popular approach in C programming, particularly when dealing with low-level tasks such as device drivers or networking protocols. The bitwise operator method involves performing bitwise operations on the decimal number to generate the corresponding binary digits.

Sample code:

#include <stdio.h>

void decToBin(int decimal) {
    int binary[32]; // array to store binary digits
    int i = 0;

    while(decimal > 0) {
        binary[i] = decimal & 1; // get the least significant bit
        decimal >>= 1; // shift the decimal number right by 1
        i++;
    }

    printf("Binary equivalent: ");

    for(int j = i - 1; j >= 0; j--) { // print binary digits in reverse order
        printf("%d", binary[j]);
    }
}

int main() {
    int decimal;

    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    decToBin(decimal);

    return 0;
}

Output:

Enter a decimal number: 25
Binary equivalent: 11001

Code Explanation:

  1. The stdio.h header file is included to allow for input/output operations.
  2. The decToBin() function is defined, which takes an integer argument decimal.
  3. An integer array binary of size 32 is declared to store the binary digits.
  4. A variable i is initialized to 0.
  5. A while loop is used to perform the bitwise operations needed to convert the decimal number to binary. Specifically, we use the bitwise AND operator (&) to get the least significant bit of the decimal number, and then we shift the decimal number right by 1 using the right shift operator (>>). We repeat this process until the decimal number becomes 0. During each iteration of the loop, we store the binary digit in the binary array and increment i.
  6. After the while loop, the binary digits are printed out in reverse order using a for loop that iterates through the binary array.
  7. In the main() function, an integer variable decimal is declared.
  8. The user is prompted to enter a decimal number using printf().
  9. The decimal number entered by the user is read in using scanf().
  10. The decToBin() function is called with the decimal variable as its argument.
  11. The program returns 0 to indicate successful execution.

2. Using division and modulo operators:

Converting decimal to binary using division and modulo operators is one of the most basic and straightforward methods in C programming. This method involves dividing the decimal number by 2 repeatedly and recording the remainders in reverse order to obtain the binary equivalent.

Sample code:

#include <stdio.h>

void decToBin(int decimal) {
    int binary[32]; // array to store binary digits
    int i = 0;

    while(decimal > 0) {
        binary[i] = decimal % 2; // get the remainder of dividing by 2
        decimal /= 2; // divide the decimal number by 2
        i++;
    }

    printf("Binary equivalent: ");

    for(int j = i - 1; j >= 0; j--) { // print binary digits in reverse order
        printf("%d", binary[j]);
    }
}

int main() {
    int decimal;

    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    decToBin(decimal);

    return 0;
}

Output:

Enter a decimal number: 25
Binary equivalent: 11001

Code Explanation:

  1. The stdio.h header file is included to allow for input/output operations.
  2. The decToBin() function is defined, which takes an integer argument decimal.
  3. An integer array binary of size 32 is declared to store the binary digits.
  4. A variable i is initialized to 0.
  5. A while loop is used to perform the division and modulo operations needed to convert the decimal number to binary. Specifically, we use the modulo operator (%) to get the remainder of dividing the decimal number by 2, and then we divide the decimal number by 2 using the division operator (/). We repeat this process until the decimal number becomes 0. During each iteration of the loop, we store the binary digit in the binary array and increment i.
  6. After the while loop, the binary digits are printed out in reverse order using a for loop that iterates through the binary array.
  7. In the main() function, an integer variable decimal is declared.
  8. The user is prompted to enter a decimal number using printf().
  9. The decimal number entered by the user is read in using scanf().
  10. The decToBin() function is called with the decimal variable as its argument.
  11. The program returns 0 to indicate successful execution.

3. Using recursive function:

In computer science, binary numbers are used to represent data and instructions in digital systems. Converting decimal numbers to binary numbers is a common task in programming. Recursive functions can be used to convert decimal numbers to binary numbers in C programming.

Sample code:

#include <stdio.h>

// Function to convert decimal to binary using recursion
void decimalToBinary(int decimalNum) {
    if(decimalNum > 0) {
        decimalToBinary(decimalNum / 2); // recursive call
        printf("%d", decimalNum % 2); // print the remainder (0 or 1)
    }
}

int main() {
    int decimalNum;
    printf("Enter a decimal number: ");
    scanf("%d", &decimalNum);
    printf("Binary number is: ");
    decimalToBinary(decimalNum); // call the recursive function
    printf("\n");
    return 0;
}

Output:

Enter a decimal number: 10
Binary number is: 1010

Code Explanation:

  1. The program prompts the user to input a decimal number.
  2. The program calls a recursive function named decimalToBinary to convert the decimal number to binary.
  3. The decimalToBinary function takes an integer parameter decimalNum which represents the decimal number to be converted to binary.
  4. Within the decimalToBinary function, there is an if statement that checks if the decimalNum is greater than zero.
  5. If decimalNum is greater than zero, the function makes a recursive call to itself with decimalNum divided by two as the parameter.
  6. The recursive call continues until decimalNum becomes zero.
  7. When decimalNum becomes zero, the function returns to the previous call stack.
  8. At each recursive call, the function prints the remainder of decimalNum divided by 2, which is either 0 or 1.
  9. As the recursive calls return, the function prints the remainder digits of the binary number.
  10. The main function calls the decimalToBinary function and prints the resulting binary number to the console.

4. Using lookup tables:

 In computer science, converting decimal numbers to binary is a common task. One way to perform this conversion in C programming is by using lookup tables. This method involves precomputing a table of binary values for all possible decimal numbers, and then looking up the corresponding binary value for a given decimal number.

Sample code:

#include <stdio.h>

// define a lookup table for binary values of decimal digits
const int binary_table[] = { 0b0, 0b1, 0b10, 0b11, 0b100, 0b101, 0b110, 0b111 };

int main() {
    int decimal_num, binary_num = 0, i = 0;

    printf("Enter a decimal number: ");
    scanf("%d", &decimal_num);

    // convert decimal to binary using lookup table
    while (decimal_num > 0) {
        binary_num += binary_table[decimal_num % 8] * (1 << i); // use modulo 8 to get the corresponding binary value
        decimal_num /= 8; // divide decimal by 8 to get the next digit
        i++;
    }

    printf("The binary equivalent is: %d\n", binary_num);
    return 0;
}

Output:

Enter a decimal number: 23
The binary equivalent is: 10111

Code Explanation:

  1. Define a lookup table for binary values of decimal digits. Each element in the table represents the binary value of the corresponding decimal digit (e.g., binary_table[1] is 0b1, binary_table[2] is 0b10, etc.).
  2. Declare variables decimal_num, binary_num, and i to store the input decimal number, output binary number, and index of the current digit, respectively.
  3. Ask the user to input a decimal number using printf() and scanf().
  4. Convert the decimal number to binary using the lookup table and a loop that iterates over each digit. For each digit, use the modulo operator % to get the corresponding binary value from the lookup table, and multiply it by 2^i (using the bit-shift operator <<) to shift the binary value to the correct position in the binary number. Then, add the shifted binary value to the binary_num variable. Finally, divide the decimal number by 8 to get the next digit, and increment the index i.
  5. Print the binary number using printf().

Note that this implementation uses octal numbers (base 8) instead of binary numbers (base 2) in the lookup table, since each octal digit corresponds to exactly 3 binary digits. However, the conversion process is still the same as for binary numbers.

5. Using library functions:

In computer science, converting decimal numbers to binary is a common task. One way to perform this conversion in C programming is by using library functions. This method involves using the printf() function with the %b format specifier to directly print the binary representation of a decimal number.

Sample code:

#include <stdio.h>

int main() {
    int decimal_num; // declare a variable to store the input decimal number

    printf("Enter a decimal number: "); // ask the user to input a decimal number
    scanf("%d", &decimal_num); // read the decimal number from standard input and store it in decimal_num variable

    printf("The binary equivalent is: %b\n", decimal_num); // use the %b format specifier to print the binary representation of decimal_num

    return 0; // return 0 to indicate successful execution of the program
}

Output:

Enter a decimal number: 23
The binary equivalent is: 10111

Code Explanation:

  1. Declare a variable decimal_num to store the input decimal number.
  2. Ask the user to input a decimal number using printf() and scanf().
  3. Convert the decimal number to binary using the %b format specifier in the printf() function. The %b format specifier is a non-standard extension of the C standard library that prints an integer in binary format. Note that not all compilers may support this extension.
  4. Print the binary number using printf().
  5. Return 0 to indicate successful execution of the program.

Note that this implementation uses a non-standard library extension and may not work on all compilers. In addition, this method only prints the binary representation of a decimal number and does not store it in a variable. If you need to store the binary representation, you may need to use other methods such as bit manipulation or string conversion.

Best approach out of five

Using the itoa() function can be a convenient and efficient way to convert decimal to binary in C, especially if the binary representation needs to be stored as a string for further processing.

  1. Efficiency: Library functions are usually optimized for performance and can execute faster than custom implementation.
  2. Reliability: Library functions have been tested and used extensively, making them more reliable than custom implementation which may contain errors or bugs.
  3. Portability: Library functions are usually designed to work on different platforms, ensuring portability and compatibility across different systems.
  4. Convenience: Library functions are easy to use and require minimal coding effort. You only need to call the function and pass the decimal number as an argument, making it a convenient solution.
  5. Standardization: Library functions for decimal to binary conversion are often part of the standard C library, making them widely available and standardized.

Sample Problems

Lets learn how to change decimal to binary in c with help of some sample problems.

Sample Problem 1:

Write a C program that prompts the user to enter a decimal number and then prints out its binary equivalent using bitwise operators.

Solution:

  1. Prompt the user to enter a decimal number.
  2. Declare variables to hold the decimal and binary numbers.
  3. Initialize the binary number to 0 and a base variable to 1.
  4. Divide the decimal number by 2 and store the remainder.
  5. Multiply the remainder with the base variable and add it to the binary number.
  6. Multiply the base variable by 10 to shift its position.
  7. Repeat steps 4-6 until the decimal number is reduced to 0.
  8. Print the binary equivalent.
  9. Terminate the program using return statement.

Code:

#include <stdio.h>

int main() {
    int decimal, binary = 0, base = 1, remainder;

    // Prompt user to enter decimal number
    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    // Convert decimal to binary
    while (decimal > 0) {
        remainder = decimal % 2;
        binary = binary + (remainder * base);
        decimal = decimal / 2;
        base = base * 10;
    }

    // Print binary equivalent
    printf("Binary equivalent: %d\n", binary);

    return 0;
}

Output:

Enter a decimal number: 556
Binary equivalent: 1000101100

Sample Problem 2:

Write a function in C that takes a decimal number as its input and returns its binary equivalent as a string using division and modulo operators.

Solution:

  1. Declare a function called decimal_to_binary that takes an integer decimal as its input and returns a string representing its binary equivalent.
  2. Allocate memory for the binary string using malloc and initialize a remainder and index variable.
  3. Use a while loop to convert decimal to binary. In each iteration of the loop, compute the remainder of the decimal divided by 2 using the % operator, add it to the binary string by converting it to a character using ASCII code, and increment the index variable. Divide decimal by 2 using the / operator. Once the loop finishes, add a null terminator to the end of the string.
  4. Reverse the binary string by swapping the characters at the front and back of the string using a for loop that iterates half the length of the string.
  5. Return the binary string.
  6. In the main function, prompt the user to enter a decimal number and read the input using scanf.
  7. Call the decimal_to_binary function with the decimal number as an argument and assign the returned string to a pointer variable.
  8. Print the binary equivalent string using printf.
  9. Deallocate the dynamically allocated memory for the binary string using free.

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* decimal_to_binary(int decimal);

int main() {
    int decimal;
    char* binary;

    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    binary = decimal_to_binary(decimal);
    printf("Binary equivalent: %s\n", binary);

    free(binary); // Free the dynamically allocated memory

    return 0;
}

char* decimal_to_binary(int decimal) {
    int remainder, i = 0;
    char *binary_str = malloc(32 * sizeof(char)); // Allocate memory for the binary string

    // Convert decimal to binary
    while (decimal > 0) {
        remainder = decimal % 2;
        binary_str[i++] = remainder + '0';
        decimal = decimal / 2;
    }
    binary_str[i] = '\0'; // Add null terminator to the end of the string

    // Reverse the binary string
    int len = strlen(binary_str);
    for (int j = 0; j < len / 2; j++) {
        char temp = binary_str[j];
        binary_str[j] = binary_str[len - j - 1];
        binary_str[len - j - 1] = temp;
    }

    return binary_str;
}

Output:

Enter a decimal number: 89
Binary equivalent: 1011001

Sample Problem 3:

Write a C program that converts a decimal number to a binary number using recursion.

Solution:

  1. The main function prompts the user to enter a decimal number and reads it using scanf.
  2. The decimal_to_binary function is then called with the decimal number as its argument.
  3. If the decimal number is equal to 0, the function returns immediately.
  4. Otherwise, the function recursively calls itself with decimal / 2 as the argument until the base case of decimal == 0 is reached.
  5. During the recursive calls, the function prints out the remainder of decimal / 2, which is the binary digit, using printf. The digits are printed out in reverse order because the function makes the recursive calls before printing the binary digits.
  6. After all the recursive calls are made, the binary number is printed out in the correct order.

Code:

#include <stdio.h>

// Function prototype for decimal_to_binary
void decimal_to_binary(int decimal);

int main() {
    int decimal;

    // Prompt the user to enter a decimal number and read it using scanf
    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    // Print a message indicating that the binary equivalent will be printed next
    printf("Binary equivalent: ");

    // Call decimal_to_binary with the decimal number as an argument
    decimal_to_binary(decimal);

    return 0;
}

// Function definition for decimal_to_binary
void decimal_to_binary(int decimal) {
    // Base case: If decimal is 0, return immediately
    if (decimal == 0) {
        return;
    }

    // Recursive case: Divide decimal by 2 and call decimal_to_binary with the quotient
    decimal_to_binary(decimal / 2);

    // Print the remainder of decimal divided by 2, which is the binary digit
    printf("%d", decimal % 2);
}

Output:

Enter a decimal number: 56
Binary equivalent: 111000

Sample Problem 4:

In data storage and retrieval systems, binary code is used to represent data. Write a C program to convert a decimal value to its binary equivalent for use in such systems using lookup tables.

Solution:

  1. Define a lookup table that maps decimal values to their binary equivalents. In this table, each decimal value is mapped to a binary string of fixed length.
  2. Define a function that takes a decimal value as input and converts it to binary using the lookup table. This function should first check if the decimal value is 0, in which case the binary equivalent is simply 0.
  3. Otherwise, it should use a loop to convert each nibble of the decimal value to binary and store it in an integer array.
  4. In the function, use the lookup table to convert each nibble to its corresponding binary value. To do this, you can use the nibble as an index into the lookup table and append the resulting binary string to a buffer string.
  5. Once all the nibbles have been converted, print the binary equivalent by printing the buffer string.
  6. In the main function, read in a decimal value from the user and call the function to print its binary equivalent.

Code:

#include <stdio.h>

// Lookup table for converting decimal values to binary
const char* binaryLookup[16] = {
    "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
    "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};

// Function to convert decimal to binary
void decimalToBinary(int decimal) {
    if (decimal == 0) {
        printf("Binary equivalent: 0\n");
        return;
    }
    
    int binary[32]; // Maximum 32 bits
    int i = 0;
    
    // Convert decimal to binary using lookup table
    while (decimal > 0) {
        binary[i++] = decimal % 16;
        decimal /= 16;
    }
    
    // Print binary equivalent
    printf("Binary equivalent: ");
    for (int j = i - 1; j >= 0; j--) {
        printf("%s", binaryLookup[binary[j]]);
    }
    printf("\n");
}

// Main function
int main() {
    int decimal;
    printf("Enter a decimal value: ");
    scanf("%d", &decimal);
    decimalToBinary(decimal);
    return 0;
}

Output:

Enter a decimal value: 1235
Binary equivalent: 010011010011

Sample Problem 5:

Many electronic devices, such as digital watches and calculators, use binary code to represent numbers. Write a C program to convert a decimal number to its binary equivalent for use in such devices using library functions.

Solution:

  1. Define a function to convert decimal to binary. The function should take an integer parameter representing the decimal number to be converted.
  2. Inside the function, declare an integer array to hold the binary equivalent. The array should have enough elements to store the maximum number of bits required for the binary representation of the decimal number.
  3. Use a loop to convert the decimal number to binary. Inside the loop, calculate the remainder when the decimal number is divided by 2 (the binary base) and store it in the next element of the binary array. Then, divide the decimal number by 2 and continue the loop until the decimal number is equal to 0.
  4. After the loop, print the binary equivalent by iterating over the binary array in reverse order and printing each element.
  5. In the main function, read in a decimal number from the user and call the function to print its binary equivalent.
  6. Compile and run the program to test it with various inputs.

Code:

#include <stdio.h>
#include <stdlib.h>

// Function to convert decimal to binary using library function
void decimalToBinary(int decimal) {
    int binary[32]; // Maximum 32 bits
    
    int i = 0;
    while (decimal > 0) {
        binary[i] = decimal % 2;
        decimal /= 2;
        i++;
    }
    
    // Print binary equivalent
    printf("Binary equivalent: ");
    for (int j = i - 1; j >= 0; j--) {
        printf("%d", binary[j]);
    }
    printf("\n");
}

// Main function
int main() {
    int decimal;
    printf("Enter a decimal number: ");
    scanf("%d", &decimal);
    decimalToBinary(decimal);
    return 0;
}

Output:

Enter a decimal number: 4569
Binary equivalent: 1000111011001

Conclusion

In conclusion, converting decimal to binary is a fundamental operation in computer programming. In C programming, the conversion can be achieved using various techniques. The program we developed above helps to convert decimal to binary using a simple iterative approach, where the decimal number is repeatedly divided by 2 and the remainder are stored in an array. The binary equivalent is then obtained by printing the remainders in reverse order. This program can be useful for beginners to understand the basic concepts of number systems and arithmetic operations in programming. In this blog we learnt how to convert from decimal to binary in C.