decimal to binary

can anyone tell me what is wrong with my code? its print out 100000 and then some weird symbols when i input 5 as my value. i know that at least the first number in the array should be zero because 2^9 definately does not have a mod greater than 0 when divinding into five

void decToBin(int value, char binary[10])
{
int j=0;
for(int i=9; i>=0; i--)
{
double result = pow(2.0, double (i));
int res= int(result);
if(value%res>0)
{
value-=res;
binary[j]='1';
}
else
{
binary[j]='0';
}
j++;
}

}
I hope this helps you
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
int *dec_binary(int i)
{

	int n = 0;
	int k = 1;
	int *p = NULL;
	while (i / 2) {
		k++;
		p  = (int *)realloc(p, sizeof(int) * k);
		p[n++] = i % 2;
		i /= 2;
	}

	p[n++] = i;
	p[n] = 9;


	for (int k  = 0; k < n / 2; k++) {
		int temp  = p[k];
		p[k] = p[n - k -1];
		p[n -k -1] = temp;
	}

	return p;
		
}
OP: you are not null-terminating the "binary" array, which I think you are outputting
as if it were a C-string.

Hello jsmith,

I did not understand exactly what you say...
Topic archived. No new replies allowed.