/* File binrep1.cpp Version 1 (simplified) J. Shinnerl, 10/18/99; 1/29/02. This program prints out the binary digits of an integer entered by the user at run time. Because the digits are acquired by integer division using %, they are obtained and stored in reverse order in an array. To display them in the usual order, the digits are reversed again during printing: the last digit stored in the array is the first digit printed, and the first digit stored in the array is the last digit printed. To determine the size of the array needed to hold the binary digits of any integer, we take the log2 (log base 2) of INT_MAX. INT_MAX is an integer constant defined in specifying the largest integer representable on the given operating platform. Because the library only contains log (log base-e) and log10 (log base-10), we use the base-changing formula log2(x) = log10(x)/log10(2) to express log2 in terms of log10. Deriving the base-changing formula is an easy exercise: y == log2(x) <==> x == 2^y <==> log10(x) == log10(2^y) <==> y == log10(x)/log10(2). (Note: ^ is *NOT* a C++ operator, nor is <==>.) */ #include #include #include #include using std::cout; using std::cin; using std::endl; const int NDIGITS_MAX = static_cast( log10(INT_MAX)/log10(2.0) ) + 1; int main() { cout << "\nThis program prints out the binary digits " << "of a nonnegative integer."; cout << "\nEnter a nonnegative integer (maximum " << INT_MAX << "): "; int number, count=0; bool digits[NDIGITS_MAX]; cin >> number; if (number < 0){ cout << "The number must be nonnegative!\n\n"; return EXIT_FAILURE; } do { // Store the digits in reverse order digits[count] = bool(number%2); // in the array called "digits" count = count + 1; number = number / 2; }while ( number > 0 ); while (count > 0) { count = count-1; cout << int(digits[count]); // Print out the elements of the } // array in reverse order. Having cout << endl << endl; // reversed the order twice, we obtain the // digits in the correct, original order. return EXIT_SUCCESS; } /* Sample I/O Script started on Tue Jan 29 09:49:20 2002 whale.1> a.out This program prints out the binary digits of a nonnegative integer. Enter a nonnegative integer (maximum 2147483647): -38912 The number must be nonnegative! whale.2> a.out This program prints out the binary digits of a nonnegative integer. Enter a nonnegative integer (maximum 2147483647): 0 0 whale.3> a.out This program prints out the binary digits of a nonnegative integer. Enter a nonnegative integer (maximum 2147483647): 3 11 whale.4> a.out This program prints out the binary digits of a nonnegative integer. Enter a nonnegative integer (maximum 2147483647): 6 110 whale.5> a.out This program prints out the binary digits of a nonnegative integer. Enter a nonnegative integer (maximum 2147483647): 1024 10000000000 whale.6> exit exit script done on Tue Jan 29 09:49:40 2002 */