Convert an integer to bits

It can be done only by bruteforce method by going through each bits in the integer as we need to get the output as all bits. 

Click here to debug the code.

#include <iostream>
#include <bitset>
#include <vector>
#include <climits>

using namespace std;

std::vector< int > get_bits( int x ) {
    //cout << " CHAR_BIT " << CHAR_BIT << " sizeof(int) " << sizeof(int) << endl;
    std::string chars( std::bitset< sizeof(int) * CHAR_BIT >( x )
        .to_string( char(0), char(1) ) );
    return std::vector< int >( chars.begin(), chars.end() );
}

vector<int> convert(int x) {
  vector<int> ret;
  do {
      ret.push_back(x & 1);
  }while(x>>=1);
  reverse(ret.begin(),ret.end());
  return ret;
}

template <typename T>
int printStd(T& v) {
    for (auto i = v.begin(); i != v.end(); i++) {
        cout << *i << " ";    
    } 
    cout << endl;
    return 0;
}

int main() 
{
    int x = 98;
    /* shrinked the no of bits only to accommodate x */
    vector<int> y = convert(x);
    printStd(y); 
    
    /* 32 bit representation if int. 64 bits for long */
    vector<int> z = get_bits(x);
    printStd(z); 
    
    return 0;       
}

Output:

1
2
1 1 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0


Click here to debug 


References 

SO link1


Comments