Wednesday 14 March 2012

Week 10 - displaying bits of i = 2345;



int i = 2345;
cout<<"i: "<<bits(i)<<endl;
output: i: 00000000000000000000100100101001

Here is my solution to get the above program.

#include <iostream>

using namespace std;

char* bits(int val) {
  int i = sizeof(val)*8;
  int b = i - 1;
  char* output = new char[i + 1];
  output[i] = '\0';
  for(i = b;i >= 0; i--) {
    output[b - i] = (char)!!(val & (1<<i)) + 48;
  }
 
  return output;
}

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

Thursday 9 February 2012

We were posed the following question in OOP344 today:


bool validMonth(int mon, char* errmes){
  bool res = false;
  if(mon > 0 && mon <=12){
    res  = true;
  }
  else{
    strcpy(errmes, "Invalid month (1<=month<=12)");
  }
  return res;
}
write the above function in one line:
bool validMonth(int mon, char* errmes){
  return yada yada;
}
yada yada can have only operators and one function call (no ?: operator allowed)

Here is my answer to the question:
bool validMonth(int mon, char* errmes){
  return (mon>0 && mon<=12) || !(strcpy(errmes,"Invalid month (1<=month<=12)"));
}


Tuesday 10 January 2012

First Post

This is my first blog post ever. The blog was originally created for OOP344.