
#include<iostream>
#include<iomanip>
using std::cout; using std::cin;
using std::endl; using std::setw;

void displayBits(unsigned);//prototype
void displayBits(char);//prototype
int main()
{
	
	unsigned x, y;
	cout<<"Please enter two integers: ";
	cin>>x>>y;
	cout<<"The bitwise values are as follows:\n";
	displayBits(x);
	displayBits(y);
	cout<<endl<<"Apply bitwise & to get this:\n";
	displayBits(x & y);
	cout<<"Apply bitwise | to get this:\n";
	displayBits(x|y);
	cout<<"Let's right-shift x by 1:\n";
	displayBits(x>>1);
	cout<<"and again:\n";
	displayBits(x>>2);
	cout<<"The exclusive-or, ^, does this:\n";
	displayBits(x^y);
	char letter;
	cout<<"Please enter a character: ";
	cin>>letter;
	cout<<"The bits used to store that character as an ASCII value are:\n";
	displayBits(letter);

	
	

	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;
}
		
void displayBits(char value)
{
	const int SHIFT=8*sizeof(char)-1;
	const char MASK='@'<<1;/* MASK has a 1 in leftmost position, 
				  and 0's otherwise. This follows from the
				  fact that the ASCII code for '@' is 64, 
				  and char's are stored in 1 byte. */

	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;
}
