
#include<iostream>
#include<iomanip>
using std::cout; using std::cin;
using std::endl; using std::setw;

void displayBits(unsigned);//prototype
int main()
{
	cout<<"\nA bool requires "<<sizeof(bool)<<" byte.\n";
	cout<<"\nAn unsigned requires "<<sizeof(unsigned)<<" bytes.\n";
	cout<<"\nAn int requires "<<sizeof(int)<<" bytes.\n";
	cout<<"\nA long requires "<<sizeof(long)<<" bytes.\n\n\n";

	unsigned inputValue;
	cout<<"Please enter an unsigned integer or <CTRL>-D to stop: ";
	while(cin>>inputValue)
	{
		displayBits(inputValue);
		cout<<"The 1's complement is \n";
		displayBits(~inputValue);
		cout<<"Note the result of adding the value, "<<
			"its 1's complement, and 1:\n";
		displayBits(inputValue+~inputValue+1);
	/* Try entering a negative value. You may see that it is interpeted
	 * as the 2's complement of the base value. That is, the 1's and 0's 
	 * are reversed, then 1 is added in binary. The third line of output 
	 * shows why. A value and its 2's complement add up to zero when you
	 * drop the carry bit.
	 */
	}
	
	

	return 0;
}

void displayBits(unsigned value)
{
	const int SHIFT=8*sizeof(unsigned)-1;
	const unsigned MASK=1 << SHIFT;/* MASK has a 1 in leftmost position, 
					  and 0's otherwise. */

	cout<<setw(10)<<value<<" = ";
	
	for( unsigned i=1; i<=SHIFT+1; i++)
	{
		cout<<(value & MASK? '1':'0');
		value<<=1;//Shift value left by one.
		if(i%8==0)
			cout<<" ";
	
	}
	cout<<endl;
}
		
	
