#include #include #include int find_significant_bits( long long n ) { if ( n < 0 ) n = -n; unsigned max_bit_pos = 0; // find the position of the left-most bit that has the value `1': for ( unsigned i = 0; i < sizeof( long long ) * CHAR_BIT; ++i ) { if ( n & ( 1LL << i ) ) max_bit_pos = i; } // We are dealing with signed numbers, // so we need one more bit for the sign ++max_bit_pos; if ( max_bit_pos < CHAR_BIT ) return CHAR_BIT; else if ( max_bit_pos < sizeof( short ) * CHAR_BIT ) return sizeof( short ) * CHAR_BIT; else if ( max_bit_pos < sizeof( int ) * CHAR_BIT ) return sizeof( int ) * CHAR_BIT; else if ( max_bit_pos < sizeof( long ) * CHAR_BIT ) return sizeof( long ) * CHAR_BIT; else return sizeof( long long ) * 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; }