decimal to binary conversion as a c-string (made simple?)

I already found some help with decimal to binary convdersion, but much of what I found didn't pertain completely to what I need.

The question and my code(not even sure if im on the right track) is as follows:

Write a function called decToBinaryString that recieves a non-negative int and returns a string that is a binary representation of the number input.
tips - concatenate strings together
test odd/even using %
write a main() that test the code

Im only getting an output of 1 regardless of what I input for even numbers (still working on odd numbers)

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<cstring>
using namespace std;

void decToBinaryString(long int, char *);

#define ARRAY_SIZE 1001

int main()
{
    long int number;
    char binary[ARRAY_SIZE];
    int count = 0;

    cout << "Enter a non-negative integer no longer than \n" << ARRAY_SIZE-1 << " integral places to convert to binary: ";
    cin >> number;
    if(number >= 0)
    decToBinaryString(number, binary);
    else
    cout << "Enter a non-negative number" << endl;
    
    cout << "Binary representation: ";
    while(binary[count] != '\0')
    {
        cout << binary[count];
        count++;
    }
    
    system ("pause");
    return 0;
}

void decToBinaryString(long int num, char *bin)
{
    int remainder, decimal, i;
    char tempArray[ARRAY_SIZE];
     
    if(num%2 == 0)              //even
    {
        do
        {
            remainder = num%2;
            num = num/2;
            itoa(remainder, bin, 10);
            bin[i++]; 
        }while(num > 0);    
    }
    else                        //(nonNeg%2 != 0) odd
    cout << "this will be for odd numbers";
    
                  
}
This line does nothing other than increment the variable i, whose value is a) undefined and b) unused.

 
            bin[i++];



To convert the integer 0 to the character '0' you can simply add '0' to the integer.
Topic archived. No new replies allowed.