C program to convert decimal to binary

C program to convert decimal to binary

  Decimal to binary conversions

In this section, we can convert any decimal number(base 10) into binary number(base 2) by c program and with example.

Example: Program to convert Decimal to Binary

#include<conio.h>

#include<stdio.h>

#include<math.h>

int main()
{
clrscr();
int decimal;
printf(“\nEnter the decimal number: “);
scanf(“%d”, &decimal);
printf(“\nBinary number is %d”, decimal2binary(decimal));
getche();
return 0;
}

long decimal2binary(int decimal)
{
long binary=0;
int rem, temp=1;
while(decimal!=0)
{
rem=decimal%2;
decimal=decimal/2;
binary=binary+rem*temp;

temp=temp*10;
}
return binary;
}


PRACTICE PROBLEMS BASED ON DECIMAL TO BINARY CONVERSION-


Convert the following numbers from base 10 to base 2

  1. (18)10
  2. (18.625)10
  3. (172)10

 

Solution-

 

1. (18)10

 

(18)10 → ( ? )2

 

Using division method, we have-

 

 

From here, (18)10 = (10010)2

 

2. (18.625)10

 

(18.625)10 → ( ? )2

 

Here, we treat the real part and fractional part separately-

 

For Real Part-

 

  • The real part is (18)10
  • We convert the real part from base 10 to base 2 using division method same as above.

 

So, (18)10 = (10010)2

 

For Fractional Part-

 

  • The fractional part is (0.625)10
  • We convert the fractional part from base 10 to base 2 using multiplication method.

 

Using multiplication method, we have-



Explanation

 

Step-01:

 

  • Multiply 0.625 with 2. Result = 1.25.
  • Write 1 in real part and 0.25 in fractional part.

 

Step-02:

 

Multiply 0.25 with 2. Result = 0.50.
Write 0 in real part and 0.50 in fractional part.

 

Step-03:

 

  • Multiply 0.50 with 2. Result = 1.0.
  • Write 1 in real part and 0.0 in fractional part.

 

Since fractional part becomes 0, so we stop.

 

  • The fractional part terminates to 0 after 3 iterations.
  • Traverse the real part column from top to bottom to obtain the required number in base 2.

 

From here, (0.625)10 = (0.101)2

 

Combining the results of real part and fractional part, we have-

(18.625)10 = (10010.101)2

 



Post a Comment

Previous Post Next Post