This C program takes a binary (base-2) number as input and finds its decimal (base-10) equivalent.
The program reads the binary value that is input by the user into a character array. The program also validates the input by checking if the characters are either 0 (ASCII 48) or 1 (ASCII 49). Any other character in the input will be ignored.
The equivalent decimal number is obtained by multiplying each binary digit by the 2's power according to its position and taking the sum of it all. So for example, binary 1101 can be converted to decimal as below:
Binary | 1 | 1 | 0 | 1 |
2s Power | 23 | 22 | 21 | 20 |
Decimal = Σ | 1 * 23 | 1 * 22 | 0 * 21 | 1 * 20 |
Decimal = | 13 |
Program Source Code
/* ****************************************** * C program to convert Binary to Decimal * ********************************************/ #include <stdio.h> #include <math.h> int main() { int dec, i, j, ch, p; char bin[30]; //Initialize the variables i=0; p=0; dec=0; // Read a Binary value (max length 30) printf("Enter a binary value : "); while ((ch=getchar()) != '\n') { //Check if input is made of 0s(ASCII 48) and 1s (ASCII 49) if (ch == 48 || ch == 49 ) bin[i++] = ch; } // Convert Binary to Decimal // Repeat for each binary digit starting from the last array element for (j = i-1; j >= 0; j-- ) { dec += (bin[j] - 48) * (int)pow((double)2, p); //Increment the position variable p++; } // Print the decimal value printf("Decimal value is : %d",dec); // Wait for key press printf("\n\nPress any key to continue..."); getchar(); return 0; }
Sample Output
Enter a binary value : 1101 Decimal value is : 13 Press any key to continue...