Archive for March 12, 2012

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;
}