#include
int IsOne(unsigned int A, int n){
return A & (1<< (n-1));
}
void prnBits(unsigned int A){
int i;
for(i=sizeof(unsigned int)*8; i>0;i--){
printf("%d", !!IsOne(A, i));
}
putchar('\n');
}
int main(void){
char A = 0x9c;
prnBits(A);
return 0;
}
~
~
output:
11111111111111111111111110011100
//An alternative way of doing this:
#include
void prnBits(unsigned int A){
int i;
for(i=1;i<=sizeof(unsigned int)*8; i++){
printf("%d", (A>>(32-i))&1);
}
putchar('\n');
}
int main(void){
char A = 0x9c;
prnBits(A);
return 0;
output:
11111111111111111111111110011100
// An example for 'Exception Handling' from website
#include
using namespace std;
class NegativeNumber
{
public:
NegativeNumber( );
NegativeNumber(string
take_me_to_your_catch_block);
string get_message( );
private:
string message;
};
class DivideByZero
{ };
int main( )
{
int jem_hadar, klingons;
double portion;
try
{
cout << "Enter number of Jem Hadar warriors:\n";
cin >> jem_hadar;
if (jem_hadar < 0)
throw NegativeNumber("Jem Hadar");
cout << "How many Klingon warriors do you have?\n";
cin >> klingons;
if (klingons < 0)
throw NegativeNumber("Klingons");
if (klingons != 0)
portion = jem_hadar/double(klingons);
else
throw DivideByZero( );
cout << "Each Klingon must fight " << portion << " Jem Hadar.\n";
}
catch(NegativeNumber e)
{
cout << "Cannot have a negative number of " << e.get_message( ) << endl;
}
catch(DivideByZero)
{
cout << "Today is a good day to die.\n";
}
cout << "End of program.\n";
return 0;
}
catch(...) //can catch any type of exception
{
cout << "Unexplained exception.\n";
}