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

No comments:

Post a Comment