// Code to see the internal representation of an integer (signed or unsigned) // Author: Sanjiv K. Bhatia // Date : February 27, 2003 #include // Count the number of bits used to represent an integer // We do not want to use sizeof() operator; why? uint num_bits_in_int() { uint i ( 1 ); // Initialize integer to 1 uint c ( 1 ); // Initialize count to 1 while ( i <<= 1 ) // Look for overflow after shift left c++; return ( c ); } // Main function int main() { using namespace std; int num; // input number cout << "Please enter a number: "; cin >> num; uint nbits = num_bits_in_int(); uint mask ( 1 << ( nbits - 1 ) ); // Mask initialized with MSB set cout << "The binary representation of " << num << " is: "; for ( uint i ( 0 ); i < nbits; i++ ) { if ( ! ( i % 4 ) ) cout << " "; // Space after four bits cout << ( ( num & mask ) ? 1 : 0 ); // Get appropriate bit in number mask >>= 1; // Move bit in mask } cout << endl; // Hex representation; just for kicks cout << "The hex representation of " << num << " is: " << hex << num << endl; return ( 0 ); }