#include #include #include int find_significant_bits( long long n ) { if ( n < LONG_MIN || n > LONG_MAX ) { return sizeof( long long ) * CHAR_BIT; } else if ( n < INT_MIN || n > INT_MAX ) { return sizeof( long ) * CHAR_BIT; } else if ( n < SHRT_MIN || n > SHRT_MAX ) { return sizeof( int ) * CHAR_BIT; } else if ( n < SCHAR_MIN || n > SCHAR_MAX ) { return sizeof( short ) * CHAR_BIT; } else { return sizeof( char ) * CHAR_BIT; } } void print_binary( long long n, int nbits ) { for ( int i = nbits - 1; i >= 0; --i ) { if ( i && i < nbits - 1 && ( i + 1 ) % 4 == 0 ) std::cout << ' '; if ( n & ( 1LL << i ) ) std::cout << 1; else std::cout << 0; } std::cout << " (bin) \n"; } int main( void ) { long long num; int bits_to_use; std::cout << "Enter a positive or negative number: "; if ( ! ( std::cin >> num ) ) { std::cerr << "Unable to read a number; giving up\n"; exit( 1 ); } bits_to_use = find_significant_bits( num ); std::cout << num << " (dec) = "; print_binary( num, bits_to_use ); std::cout << num << " == " << std::hex << std::showbase << num << std::dec << '\n'; return 0; }