Instructions
Objective
Write a program that allows users to Convert integer values to binary with variable number of bits in C++.
Requirements and Specifications
Screenshots of output
Source Code
#include
using namespace std;
int main()
{
int number, nbits;
char option;
cout << "Your name" << endl;
cout << "Excess M Converter Program:" << endl;
bool terminate = false;
while (!terminate) // repeat until user chooses to terminate
{
cout << "****************************************" << endl;
cout << "Input an integer number: ";
cin >> number;
cout << "\nInput a number of bits: ";
cin >> nbits;
int range_high = (1 << (nbits - 1)); // upper range = 2^(nbits - 1)
int range_low = - (range_high - 1); // lower range = -2^nbits
cout << "\nThe range is: " << range_low <<" to " << range_high << " (inclusive)." << endl;
if (number < range_low || number > range_high) // check if number is in range
cout << number << " is out of range" << endl;
else
{
cout << number << " = ";
// convert number to binary
number = number - range_low; // add excess
int mask = range_high; // start with a bitmask at most significant bit
for (int i = 0; i < nbits; i++) // print the bits
{
int bit = mask & number; // isolate the bit
if (bit != 0) // print the corresponding number 1 or 0
cout << "1";
else
cout << "0";
mask = mask >> 1; // move mask to isolate next bit to the right
}
cout << endl;
cout << "Do you want to continue (Y/y)? ";
cin >> option;
if (option != 'Y' && option != 'y')
terminate = true; // terminate program
}
}
return 0;
}