Convert integer to binary and store it in an integer array of specified size:c++

Pseudo code:

int value = ????  // assuming a 32 bit int
int i;

for (i = 0; i < 32; ++i) {
    array[i] = (value >> i) & 1;
}

template<class output_iterator>
void convert_number_to_array_of_digits(const unsigned number, 
         output_iterator first, output_iterator last) 
{
    const unsigned number_bits = CHAR_BIT*sizeof(int);
    //extract bits one at a time
    for(unsigned i=0; i<number_bits && first!=last; ++i) {
        const unsigned shift_amount = number_bits-i-1;
        const unsigned this_bit = (number>>shift_amount)&1;
        *first = this_bit;
        ++first;
    }
    //pad the rest with zeros
    while(first != last) {
        *first = 0;
        ++first;
    }
}

int main() {
    int number = 413523152;
    int array[32];
    convert_number_to_array_of_digits(number, std::begin(array), std::end(array));
    for(int i=0; i<32; ++i)
        std::cout << array[i] << ' ';
}

Proof of compilation here


You could use C++'s bitset library, as follows.

#include<iostream>
#include<bitset>

int main()
{
  int N;//input number in base 10
  cin>>N;
  int O[32];//The output array
  bitset<32> A=N;//A will hold the binary representation of N 
  for(int i=0,j=31;i<32;i++,j--)
  {
     //Assigning the bits one by one.
     O[i]=A[j];
  }
  return 0;
}

A couple of points to note here: First, 32 in the bitset declaration statement tells the compiler that you want 32 bits to represent your number, so even if your number takes fewer bits to represent, the bitset variable will have 32 bits, possibly with many leading zeroes. Second, bitset is a really flexible way of handling binary, you can give a string as its input or a number, and again you can use the bitset as an array or as a string.It's a really handy library. You can print out the bitset variable A as cout<<A; and see how it works.

Tags:

C++

Binary