Decimal Integer to Binary

The following code converts an integer to a binary number represented by an
int array.


// Convert a decimal integer to a binary

#include
using namespace std;
#include
#include

static int bin[32];

void decToBin(int n)
{
    if (n == 0) return;
    int temp = n;
    int pos = 0;
    n /=2;
    while (n != 0)
    {   
        pos++;
        n= n/2;

    }   
    bin[31-pos] = 1;
    decToBin(temp-pow(2, pos));
    
}

int main()
{
    for (int i = 0; i < 32 ; ++i) bin[i] = 0;
    int n = 45672345;
    decToBin(n);
    for (int i = 0; i < 32; ++i) cout << bin[i] ;
    cout << endl;
    

    bitset<32> b(45672345);
    cout << b << endl;


  return 0;
}


No comments: