Cout bits

Posted: March 12, 2012 in OOP344
#include <iostream>
#include <string>
using namespace std;

string bits(int val){
  string A="01";
  string ret;
  for(int i = sizeof(int)*8-1; i >= 0; i--, val>>=1)
    ret = A[val & 1] + ret;
  return ret;
}

string bitsTrim(int val){
  string ret;
  do{
    ret = (char)(!!(val & 1)+48) + ret;
    val>>=1;
  }while(val);
  return ret;
}

int main()
{
  int x = 2345;
  cout << "Binary:  " << bits(x) << endl;
  cout << "Binary:  " << bitsTrim(x) << endl;
  return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s