Here's a C program to convert a binary number to a decimal number with output and proper explanation. This program makes use of C concepts like While loop, IF-Else and Modulus. The program also uses C's math.h header file and power function pow(i, j).
# include <stdio.h>
# include <conio.h>
# include <math.h>
void main()
{
int i = 0, j = 0, sum = 0 ;
long int n ;
clrscr() ;
printf("Enter the binary number : ") ;
scanf("%ld", &n) ;
if(n > 0)
{
i = n % 10 ;
if(i == 0 || i == 1)
{
while(n != 0)
{
i = n % 10 ;
sum = sum + i * pow(2, j) ;
n = n / 10 ;
j ++ ;
}
}
}
if(sum == 0 && n < 0)
printf("\nThe number is not a binary number") ;
else
printf("\nThe equivalent decimal number is : %d", sum) ;
getch() ;
}
Output of above program is
Enter the binary number : 1100
The equivalent decimal number is : 12
Enter the binary number : 12
The number is not a binary number
How to convert binary number to decimal? Here's a basic method to convert a binary number to decimal form. Suppose there are n digits in your binary number. So the formula to get decimal equivalent of this binary number is - (Here nth digit is the leftmost digit and 1st digit is the rightmost digit.)Decimal number = (value of nth digit) * 2 (n-1) + (value of n-1 th digit) * 2 (n-2) + (value of n-2 th digit) * 2 (n-3) +........ + (value of 1st digit) * 2 (0)e.g. b = 10010. The decimal value is -Decimal number = 1 * 2 4 + 0 * 2 3 + 0 * 2 2 + 1 * 2 1 + 0 * 2 0 = 16 + 2 = 18.
Explanation of above program
Our program also uses the same process described above. We are using Math.H header file for the mathematics function pow(i, j) to calculate power.
This comment has been removed by the author.
ReplyDeletecan u find the decimal form of 00 using this program?...it will display that 00 is not a binary number right??..as cntrl didnt go in2 the loops..n sum is still 0...
ReplyDeleteYes @fboys123, you're right and thank you for pointing it out. It will print "The number is not a binary number" in case of n = 0.
ReplyDeleteSee the changes that I made and let me know if there's still any problem with it.
jigaaaaar chaaaaa gaya hai :D
ReplyDeletebhai ki assignment banwa di tu nay tou :D
Binary number system is a base 2 number system using digits 0 and 1 whereas Decimal number system is base 10 and using digits from 0 to 9. Here is the a program to convert Binary to Decimal number
ReplyDeleteHowdy Mate,
ReplyDeleteGrazie! Grazie! Grazie! Your blog is indeed quite interesting around I agree with you on lot of points!
A subset of a natural language contains these sentences:
1) Triangle ABC.
2) Line Segment AB.
3) Angle A.
In this set, names of triangles are formed by putting three letters together,
all drawn from the alphabet {A,B,C,D,E}. Line segment names are defined by
putting two letters together from the previous alphabet. And angle names are
(suprise!) given by any letter in that alphabet.
Great effort, I wish I saw it earlier. Would have saved my day :)
Thank you,