/* ************************************************************************** * Program name : 015_Binary_to_Decimal (Version 1.00) * * Author : Duck Wong * * Language : C / C++ * * Compiler : Boodshed Dec-C++ compiler Ver 3.95 * * Computer : PII350 * * O/S : Windows 98 * ************************************************************************** * Version 1.00 : 2000/06/09 - first version * ************************************************************************** * Description : (a) input the a binary number * * (b) convert to decimal number * * (c) try again ? * ************************************************************************** */ #include #include int main() { // part 1 : declaration int Bin, Dec, TempBin; int div; char valid, again; do { // part 2 : Repeat asking the value of the binary number Bin = TempBin = 0; do { cout << "Please input a binary number (1 to 10 bits) : "; cin >> Bin; TempBin = Bin; do { if ((TempBin % 10)==0 || (TempBin % 10)==1) // Note (1) valid='Y'; else { cout << "Invalid pattern! use 0's and 1's only\n\n"; valid='N'; break; }; TempBin = (TempBin/10); } while (TempBin>0); } while (valid=='N'); // part 3 : Convertion div = 1; Dec = 0; TempBin = Bin; do { Dec += (TempBin % 10)*div; // Note (2) div *= 2; TempBin = (TempBin/10); } while (TempBin>0); cout << "\nThe binary pattern " << Bin << " is equal to " << Dec << " in decimal pattern.\n" << endl; // part 4 : try another number ? cout << "\aTry another number (Y/N) : "; cin >> again; cout << "\n"; } while (again=='Y' || again=='y'); cout << "\n" << endl; system("PAUSE"); return 0; } /* Notes (1) If the remainder of TempBin over 10 is not zero or one, then the program think that the binary pattern is invalid. Example : Let's the value of TempBin is 1201 , then Round TempBin Remainder Action ---------------------------------------------------------------- 1 1201 1 adjuct the value of TempBin to 120 2 120 0 adjuct the value of TempBin to 12 3 12 2 Error found! Stop the loop of checking invalid digit the this binary pattern. (2) Convertion : The line "Dec += (TempBin % 10)*div;" find the new value of Dec. The line "div *= 2;" adjust/update the value of div for the next round. The line "TempBin = (TempBin/10);" adjust/update the value of TempBin for the next round. Example : Let's the value of TempBin is 1101 , then Round Remainder div Old_Dec New_Dec New_div ---------------------------------------------------------------- 1 1 1 0 1*1+0=1 2 2 0 2 1 0*2+1=1 4 3 1 4 1 1*4+1=5 8 4 1 8 5 1*8+5=13 16 */