# Thread: Decimal to Binary conversion help

1. ## Decimal to Binary conversion help

This is my code and this is my logic

Code:
```#include "stdafx.h"
#include "stdio.h"
#define SIZE 7

int main()
{

int array1[SIZE];
int dec;
int c;

printf("decimal: ");
scanf(" %d", &dec);
for(c=0;c<=7;c++)
{
array1[c]=dec%2;
dec=dec/2;
}
printf("\n\nThis is the binary number %d\n\n", array1[SIZE]);
system("pause");
}```
I can not get the array to shift so I think the binary bits are overriding each other. I also get an error message saying that the stack around the variable array1 was corrupted. Any suggestions?

2. Code:
`for(c=0;c<=7;c++)`
While there are 7 elements in your little array, they're zero-indexed. That is start from zero and go to n - 1, in this case 6.

Code:
`for(c = 0; c < (sizeof(array1) / sizeof(array1[0])); c++)`
or
Code:
`for(c = 0; c < SIZE; c++)`
Is suffice, try and avoid magic numbers.

3. Originally Posted by tru.cutru
I also get an error message saying that the stack around the variable array1 was corrupted. Any suggestions?
You are getting stack corruption because you are writing at array[7], which means the 8th element of array, but your array only has 7 elements. Basically, when you are doing "array[7] = ...;" you are writing somewhere you shouldn't.

I can not get the array to shift so I think the binary bits are overriding each other.
Well, when you do

Code:
`printf("\n\nThis is the binary number %d\n\n", array1[SIZE]);`
you are only printing the (SIZE+1)th element of array1.

Iif you want to output the "binary value" your array holds, then you have to successively output each element of your array. Start by printing the highest element (array[6]), finish with the lowest (array[0]).

There's also some logic error in your code. Like only making an array of 7 elements (quite often, an int can hold a 32-bits number, so if your number is larger than 127, you won't print the real "binary value" of the number).

4. >printf("\n\nThis is the binary number &#37;d\n\n", array1[SIZE]);
You need a loop to print out the array. The following would print the array in reverse order:
Code:
```for (i=SIZE-1; i>=0; i--)
{
printf("%d", array1[i]);
}
printf("\n");```
Also note array1 has 7 locations:
array1[0]
array1[1]
array1[2]
array1[3]
array1[4]
array1[5]
array1[6]

So this for-loop accesses array1[7], which is out-of-bounds:
Code:
`>	for(c=0;c<=7;c++)`