Tuesday, 13 March 2012

Classical Programming - 3 : print binary numbers (c++)

#include <iostream>
using namespace std;
#define SIZE sizeof(int)*8

char* bits(int val) {
     static char str[SIZE];
     for(int i = SIZE-1; i >= 0; i--) {      
       str[(SIZE-1)-i] = (val & (1<<i)) == 0? '0':'1';
     }
     return str;
 }

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

No comments:

Post a Comment