Decimal to Binary in C

Decimal Numbers:
Decimal numbers are the numbers in the decimal system. They are represented by the digits 0 to 9. For example, the number 123 is represented by the digits 1, 2, and 3. The number 0 is represented by the digit 0. The number 123456789 is represented by the digits 1, 2, 3, 4, 5, 6, 7, 8, and 9. In order to represent number system, we need a base. Decimal numbers are represented in the base 10. The base 10 is the most common base in the world.

Binary Numbers:
Binary numbers are the numbers in the binary system. They are represented by the digits 0 and 1. For example, the number 101 is represented by the digits 1 and 0. The number 0 is represented by the digit 0. The number 101010101 is represented by the digits 0, and 1. Binary numbers are represented in the base 2.

Problem Description

Write a C program that takes a decimal number as input and convert it to a binary number.

Algorithm:
The simplest way to convert a Decimal number to Binary number is to use the following algorithm:

1. Divide the number by 2 and get the quotient and remainder.
2. If the remainder is 0, then the binary number is 0.
3. If the remainder is 1, then the binary number is 1.
4. Repeat the process for the quotient and remainder.
5. For every step keep appending the remainder to the binary number.

Problem Solution

To approach this problem, we simply use the repeated division method and take out the remainder. This program uses modulo operator to get the remainder.

There are many approaches to convert a Decimal number to Binary number. Let’s take a detailed look at all the approaches to convert a Decimal number to Binary number in C.

advertisement
advertisement

Method 1: Convert Decimal to Binary using Naive Approach (Division Operation)

This approach simply converts the decimal number to binary using the division operation and while loop.

Methods used:
decimal_to_binary – This method converts the decimal number to binary number.

Example:
Suppose the input is 324, the program should output 101000100.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Program/Source Code

Here is the source code of the C program to find the binary equivalent of the decimal number. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* 
  2.  * C Program to Convert Decimal to Binary number
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. long dec_to_bin(long n)
  8. {
  9.     long bin = 0;
  10.     long dec = n;
  11.     long i = 1;
  12.  
  13.     while (dec > 0) {
  14.         bin += (dec % 2) * i;
  15.         dec /= 2;
  16.         i *= 10;
  17.     }
  18.  
  19.     return bin;
  20. }
  21.  
  22. int main(void)
  23. {
  24.     long n;
  25.     printf("Enter a decimal number: ");
  26.     scanf("%ld", &n);
  27.     printf("Binary equivalent of %ld = %ld\n", n, dec_to_bin(n));
  28.     return 0;
  29. }
Program Explanation

1. The program starts with asking the user to enter a decimal number.
2. The program then converts the decimal number to binary number via the dec_to_bin method.
3. Here, we have to keep in mind that our program can’t convert negative numbers to binary.
4. Therefore, for numbers which are negative, we return 0 as the binary number.
5. For positive numbers, we return the binary number after performing continued division and adding the remainders to the binary number.
6. The program prints the binary number after converting the decimal number to binary.

Time complexity: O(n)
The time complexity of this program is O(n) where n is the number of digits in the decimal number.

Space Complexity: O(1)
The space complexity of this program is O(1) since we are not using any extra space.

advertisement
Run Time Testcases

Testcase 1: In this case, we are entering the decimal number “324” as input.

Enter a decimal number: 324
Binary equivalent of 324 = 101000100

Testcase 2: In this case, we are entering the decimal number “-123” as input.

Enter a decimal number: -123
Binary equivalent of -123 = 0

advertisement
Method 2: Convert Decimal (Negative Numbers) to Binary

The decimal number can be negative. For example, the number -123 is represented by the digits 1, 2, 3. The number -0 is represented by the digit 0. The number -123.456789 is represented by the digits 1, 2, 3, ., 4, 5, 6, 7, 8, and 9.

Methods used:

  • int sizeOfNumber – Used to find the size (number of digits) of the number and also the bitsize in which it should fit in.
  • long twos_complement – Finds the twos complement of the number entered as binary.
  • long dec_to_bin – Converts the decimal number to binary.
  • long toBinary – Checks whether the number is negative or not and accordingly passes it to functions.

Approach to convert decimal (neagtive number) to binary.
1. Ask the user to enter the decimal number.
2. Check whether the number is negative or not.
3. If the number is positive, then convert it to binary.
4. If the number is negative, find it’s bitsize and convert it to two’s complement.
5. Convert the decimal number to binary.
6. Print the binary number.

Examples:

Suppose the input is -123, the program should give output as 10000101.

Suppose the input is 100, the program should give output as 1100100.

Program/Source Code

Here is the source code of the C program to find the binary equivalent of the decimal negative number. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* Decimal to binary numbers also taking into account negative numbers. */
  2.  
  3. #include <stdio.h>
  4.  
  5. int bitsize = 8;
  6.  
  7. int sizeOfNumber(long n)
  8. {
  9.     // Repeated division by 10 to find the size of the number.
  10.     int size = 0;
  11.     while (n > 0)
  12.     {
  13.         n /= 10;
  14.         size++;
  15.     }
  16.     // Bitsize will be helpful while finding the two's complement
  17.     if (size > 7)
  18.         bitsize = 16;
  19.     return size;
  20. }
  21.  
  22. long twos_complement(long n)
  23. {
  24.     long i = 1;
  25.     long twos_comp = 0;
  26.     long r;
  27.     int flag = 0;
  28.     printf("The number has %d digits so setting bitsize at %d.\n", sizeOfNumber(n), bitsize);
  29.     for (int j = 0; j < bitsize; j++)
  30.     {
  31.         // Finding the remainder and appending it according to the flag.
  32.         r = n % 10;
  33.         if (flag == 1)
  34.             twos_comp += ((r == 1) ? 0 : 1) * i;
  35.         else
  36.             twos_comp += r * i;
  37.         n /= 10;
  38.         i *= 10;
  39.         if (r == 1)
  40.             flag = 1;
  41.     }
  42.     printf("The twos complement ");
  43.     return twos_comp;
  44. }
  45.  
  46. /* Simple decimal to binary convertor */
  47. long dec_to_bin(long n)
  48. {
  49.     long bin = 0;
  50.     long dec = n;
  51.     long i = 1;
  52.  
  53.     while (dec > 0)
  54.     {
  55.         bin += (dec % 2) * i;
  56.         dec /= 2;
  57.         i *= 10;
  58.     }
  59.  
  60.     return bin;
  61. }
  62.  
  63. long toBinary(long n)
  64. {
  65.     // Function to check whether it's a negative or a positive number and 
  66.     // accordingly passes through the functions.
  67.     if (n >= 0)
  68.         return dec_to_bin(n);
  69.     else
  70.         return twos_complement(dec_to_bin(~n + 1));
  71. }
  72.  
  73. int main(void)
  74. {
  75.     long n;
  76.     printf("Enter a decimal number: ");
  77.     scanf("%ld", &n);
  78.     printf("Binary equivalent of %ld = %ld\n", n, toBinary(n));
  79.     return 0;
  80. }
Program Explanation

1. The program starts with asking the user to enter a decimal number.
2. The program then converts the decimal number to binary number via the dec_to_bin method.
3. In case the number is negative, we use the twos_complement method to find the twos complement of the number and also find the bitsize.

Time complexity: O(n)
The time complexity of this program is O(n) where n is the number of digits in the decimal number.

Space Complexity: O(1)
The space complexity of this program is O(1) since we are not using any extra space.

Run Time Testcases

Testcase 1: In this case, we are entering the decimal number “-123” as input.

Enter a decimal number: -123
Binary equivalent of 324 = 10000101

Testcase 2: In this case, we are entering the decimal number “100” as input.

Enter a decimal number: 100
Binary equivalent of 100 = 1100100

Method 3: Decimal Numbers with Floating Points

The decimal number can have fractional points. For example, the number 123.45 is represented by the digits 1, 2, 3, ., 4, 5. The number 0.0 is represented by the digit 0. The number 123.456789 is represented by the digits 1, 2, 3, ., 4, 5, 6, 7, 8, and 9.

Methods used:

  • long dec_to_bin – Converts the decimal number to binary.
  • double fractBin – Converts the fractional part of the decimal number to binary.
  • long toBinary – Converts the decimal number to binary by separating the fractional part and integer part.

Approach:
1. Ask the user to enter the decimal number.
2. Separate the fractional part and integer part.
3. Send the integer part to the dec_to_bin method.
4. Send the fractional part to the fractBin method.
5. Convert the decimal number to binary.
6. Add the resulting binary numbers.
7. Print the binary number.

Example:
Suppose the input is 123.45, the program should output 1111011.011100.

Program/Source Code

Here is the source code of the C program to find the binary equivalent of the decimal number with floating points. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* We will convert decimal numbers with doubleing points to binary */
  2.  
  3. #include <stdio.h>
  4.  
  5. long dec_to_bin(long n)
  6. {
  7.     long bin = 0;
  8.     long dec = n;
  9.     long i = 1;
  10.  
  11.     while (dec > 0)
  12.     {
  13.         bin += (dec % 2) * i;
  14.         dec /= 2;
  15.         i *= 10;
  16.     }
  17.  
  18.     return bin;
  19. }
  20.  
  21. // fractBin multiplies iteratively for the fractional part of the number.
  22. double fractBin(double n)
  23. {
  24.     double bin = 0;
  25.     int threshold = 6;
  26.     double temp = n;
  27.     double j = 0.1f;
  28.  
  29.     for (int i = 0; i < threshold && temp > 0; i++)
  30.     {
  31.         temp *= 2;
  32.         int temp_int = (int)temp;
  33.         bin += (double)temp_int * j;
  34.         temp -= (double)temp_int;
  35.         j /= 10;
  36.     }
  37.  
  38.     return bin;
  39. }
  40.  
  41. double toBinary(double n)
  42. {
  43.     // Send the part after decimal point to dec_to_bin function.
  44.     long num_int = (long)n;
  45.     double bina = (double) dec_to_bin(num_int);
  46.  
  47.     double num_dec = n - (double) num_int;
  48.     double binb = fractBin(num_dec);
  49.     return bina + binb;
  50. }
  51.  
  52. int main(void)
  53. {
  54.     double n;
  55.     printf("Enter a decimal number: ");
  56.     scanf("%lf", &n);
  57.     printf("Binary equivalent of %lf = %lf\n", n, toBinary(n));
  58.     return 0;
  59. }
Program Explanation

1. The program starts with asking the user to enter a decimal number.
2. The program then converts the integer part of the decimal number to binary number via the dec_to_bin method.
3. The fractional part of the decimal number is converted to binary number via the fractBin method.
4. The resulting binary numbers are added and printed.

Let’s see how this works.

So, for the integer part, it’s already clear that the binary representation can be found out simply by repeated division with 2. However in case of fractional parts, the binary equaivalent is found out by repeated multiplication by 2. Suppose the number is 12.5, then as we’d guess the binary representation is 1100.1. For every digit to the right of the decimal point, if an decimal gets 10 different characters, binaries gets only 2. So, that’s the reason of the multiplication.

A simple analogy would be that of a jar. If we want to tell that it’s half filled, we know that in decimal terms, we’ll say it’s 0.50 filled. So, 0.50 + 0.50 is 1.00. Similarly, in case of binary we say 0.10 as, 0.10 + 0.10 = 1.00. This simple trick could be used to understand many other aspects of binaries and their relations with decimals.

Time complexity: O(n)
The time complexity of this program is O(n) where n is the number of digits in the decimal number.

Space Complexity: O(1)
The space complexity of this program is O(1) since we are not using any extra space.

Run Time Testcases

Testcase 1: In this case, we are entering the decimal number “123.45” as input.

Enter a decimal number: 123.45
Binary equivalent of 123.450000 = 1111011.011100

Testcase 2: In this case, we are entering the decimal number “3045.219” as input.

Enter a decimal number: 3045.219
Binary equivalent of 3045.219000 = 101111100101.001114

Method 4: (Recursion Approach)

The following C program using recursion finds a binary equivalent of a decimal number entered by the user.

Program/Source Code

Here is the source code of the C program to find the binary equivalent of the decimal number using recursion. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

Example:
Given decimal number = 15. Formula used to convert decimal to binary is dec % 2 + 10 * convert(dec / 2)

  • 15 % 2 that is equal to 1 + 10 * ( 15/2 ) % 2
  • 7 % 2 that is equal to 1 + 10 * ( 7/2 ) % 2
  • 3 % 2 that is equal to 1 + 10 * ( 3 / 2) % 2
  • 1 % 2 that is equal to 1 + 10 * ( 1 / 2 ) % 2

Binary number of 15 is 1111

/*  
 * C Program to Convert Decimal to Binary using Recursion
 */
 
#include <stdio.h>
 
int convert(int);
 
int main()
{
    int dec, bin;
 
    printf("Enter a decimal number: ");
    scanf("%d", &dec);
    bin = convert(dec);
    printf("The binary equivalent of %d is %d.\n", dec, bin);
 
    return 0;
}
 
int convert(int dec)
{
    if (dec == 0)
    {
        return 0;
    }
    else
    {
        return (dec % 2 + 10 * convert(dec / 2));
    }
}
Program Explanation

In this C program, we are reading a decimal number using the ‘dec’ variable. The function convert() is used to convert a number decimal system to binary system using recursion.

If else condition statement is used to check the value of ‘dec’ variable is equal to 0, if the condition is true execute the statement return null value. Otherwise if the condition is false then execute the else condition statement.

Divide the value of ‘dec’ variable by 2. Multiply the result value with 10 and add the value with the modulus of the value of ‘dec’ variable by 2. Print the Binary number of the decimal system using printf statement.

Runtime Test Cases

In this case, we are entering the decimal number “15” as input.

Enter a decimal number: 15
The binary equivalent of 15 is 1111.

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.