// File: bits.cxx // Written by: Michael Main (main@colorado.edu) // The purpose of this program is the print the bit patterns for // letters and small numbers (from 0 to 255). #include #include #include using namespace std; // void binary_pattern(int i) // This function prints the least significant 8 bits of i, // with the least significant one printed last. It then // prints a space and prints the same thing in base 16. void binary_pattern(int x) { int mask; // Throw away any bits beyond the lower 8: x &= 0xFF; // Prints the least significant 8 bits for (mask = 128; mask > 0; mask >>= 1) { cout << ((x & mask) ? '1' : '0'); } // Prints the same thing in base 16 (hexadecimal): if (x < 16) cout << " 0"; else cout << " "; cout << setbase(16) << x; } int main( ) { int number; // A number typed by the user char letter; // A letter typed by the user cout << "Please type numbers from 0-255 and letters." << endl; cout << "Press ctrl-c to end the program." << endl; while (true) { if (isdigit(cin.peek( ))) { cin >> number; if (0 <= number && number <= 255) { cout << setw(10) << number << ": "; binary_pattern(number); cout << endl; } } else if (isalpha(cin.peek( ))) { cin >> letter; cout << setw(10) << letter << ": "; binary_pattern(letter); cout << endl; } else { cin.ignore( ); } } return 0; }