Int to binary conversion

Hi,
I'm trying to write a function which takes a positive int and converts it into binary via repeatedly dividing by 2, storing the remainders in an array and printing them out in reverse.
This is what I've got so far.

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
void Dec2BinaryDivision(int a)
{
	bool begin = false;
	int rem[31]={}, i=0;
	if (a == 0) //trivial case
	{
		cout << 0;
		return;
	}
	/*for (i=0; i<32; i++)
		cout << rem[1] << " ";*/
	cout << "wat";
	do //1s and 0s into array
	{
		rem[i] = a%2;
		a = ((a/2) + rem[i]);
		i++;
	
	} while (a != 0);

	i = 31;
	
	while (!begin) //searches for the end of leading zeroes
	{
		if(1 == rem[i])
		{
			begin = true;
		}
		i--;
	}
	for (i; i>=0; i--) //prints array in reverse
	{
		cout << rem[i];
	}
	cout << endl << "wat";
	
}


Something very similar to this was somewhat functional earlier, but this only prints one 'wat' (cout << "wat" is a checkpoint) and then crashes. If anyone can see any obvious flaws in the function I'd really appreciate if you could show me.
Thanks
My guess is that you are going out of bounds on your "rem[]" array. I think you need to reexamine your math between Lines 13 and 19.
1
2
rem[i] = a%2;
a = ((a/2) + rem[i]);
1/2+1%2=1, which means that there's a 50% chance that the while loop will never finish.
It seems the problem was indeed with my code between 13 and 19. Thanks very much!
Topic archived. No new replies allowed.