// *************************************************** // * Brandon Smith // * C++ Hour 2 // * This program prompts the user to input an eight-digit binary number. Once the user // * presses Enter/Return, the program attempts to convert the binary input into decimal // * form, and displays the result to the user. // *************************************************** #include #include using namespace std; void main() { int biNum; int decForm = 0; int digit[8]; cout << "Please enter a binary number of 8 digits or less: "; //Gets an 8-digit binary number from the user and stores it in the integer decForm. cin >> biNum; /*"Extracts" each digit (up to eight digits) of the binary number, and adds its decimal value to the integer decForm. After the loop, decForm holds the decimal form of the provided binary number.*/ for(int i = 0; i < 8; i++) { /*The next two lines "extract" the binary digit at the position of integer i, and place it in the integer array digit at array index i.*/ digit[i] = (biNum/pow(10.0, 7-i)); digit[i] %= 2; /*"Converts" the current binary digit into its decimal representation, and adds it to the integer decForm.*/ decForm += digit[i]*pow(2.0, 7-i); } /*The below code was used for debugging; to check and see if each individual digit was correctly "extracted" and placed into the integer array digit.*/ /*cout << "Digit 1: " << digit[0] << "\nDigit 2: " << digit[1] << "\nDigit 3: " << digit[2] << "\nDigit 4: " << digit[3] << "\nDigit 5: " << digit[4] << "\nDigit 6: " << digit[5] << "\nDigit 7: " << digit[6] << "\nDigit 8: " << digit[7] << "\n";*/ /*Remind the user of the binary number they provided, and show them the decimal equivalent.*/ cout << "\n**************************************************\n"; cout << "The unsigned binary number: " << biNum << "\nequals the decimal number: " << decForm; cout << "\n**************************************************\n"; }