Decimal to binary conversion using a function

Hello everyone! Hope you all be fine.. I m trying to convert a decimal number to binary using a function. I tried to save the result into an array but the problem is i cannot display it backwards correctly.Please help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream.h>
long decimal2binary(int);    //Function protoype

main()
{
int dec;
cout<<"Please enter a decimal number: ";
cin>>dec;
decimal2binary(dec);   //Function Call by value

}

long decimal2binary(int num)        //Function definition
{
int i ,j, rem ,quo , bin[8] ;
 for(j=0;j<=7;j++)
 {
  rem = num%2;

  bin[8] = rem ;
  num = num/2;


 }
  for(i=7;i>=0;i--)            //Displaying the array backward
  {
  cout<<bin[i];
  }

}
1
2
3
4
5
unsigned long long decimal2bin( unsigned short n )
{
    if( n < 2 ) return n ;
    else return decimal2bin(n/2) * 10 + n%2 ;
}

http://coliru.stacked-crooked.com/a/1345761f5998c1c8
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;

string intToBin( int n ) {  return n > 0 ? intToBin( n / 2 ) + (char)( '0' + n % 2 ) : ""; }

int main()
{
   int n;
   cout << "Enter a positive integer: ";   cin >> n;
   cout << "In binary: " << intToBin( n );
}


Enter a positive integer: 1234567
In binary: 100101101011010000111
Topic archived. No new replies allowed.