25/09/2022
satyams.friend
0 Comments
Binary to Decimal Conversion in C Language
Binary to Decimal Conversion in C Language
In this section we discuss about Binary to Decimal conversion. A Binary number should we converted as following method :
Suppose we take a binary (1101)2
then we need to find place value of each digits and add them, the addition of place value is equal to the decimal equivalent of binary.
finding place value :
1 | 1 | 0 | 1 |
1 X 23=8 | 1 X 22=4 | 0 X 21=0 | 1 X 20=1 |
addition = 8 + 4 + 0 + 1 = 13
So (13)10 is the decimal equivalent of binary (1101)2
Method to convert binary to decimal
- Take a binary number as the input in variable bin.
- Divide the number by 10 and store the remainder into variable "r".
- dec = dec + r ´ b;
Initially, the "dec" is 0, and the "b" is 1, where the "r" variable stores the remainder of the number. - Divide the quotient of the original number by 10.
- Multiply the "b" by 2.
- Print the decimal of the binary number.
Note : variable dec for decimal number, b for base, r for reminder and "bin" for binary.
Souce Code :
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
int n, bin, dec=0, b=1, r;
printf ("Enter a binary number \n");
scanf ("%d", &n);
bin = n;
while ( n > 0)
{
r = n % 10;
dec = dec + r * b;
n = n / 10;
b = b * 2;
}
printf("The Decimal equivalent of %d = %d", bin, dec);
getch( );
}