0

So I'm very new to C, and I'm having trouble with my decimal to binary conversions.

I'm trying to convert 2 numbers - "205" and "171" too binary and put them both in separate arrays, and its working - sort of. See they both convert properly, but they both have three extra "1"s trailing them.

For example, when I use "printf" to see what is in the x array, it is "11001101111" instead of "11001101". The same happens with the y array.

Here's the program so far (I tried to annotate it to make it as clear as possible).

Note: I commented out the "printf" for the y array, but you can switch them out if you want.

int inputx = 205;
int inputy = 171;
//scanf("%d %d", &inputx, &inputy); //
int x[16] = {};
int y[16] = {};

//declaring variables for x conversion

int i = 0;
int d1 = 0;
int c = 0;
int a = 0;
int number1[16] = {};
//converting inputx from decimal into binary

while (inputx != 0){
    i = i+1;
    d1 = inputx % 2;
    inputx = inputx / 2;
    c++;
    number1[c]=d1;
}//end while

//since the binary array is in reverse, this loop fixes it

for(a = 0; a < c; a = a + 1 ){
    x[a]=number1[c-a];
    printf("%d", x[a]); //printf just for testing 
}//end for

//declaring variables for y conversion

i = 0;
d1 = 0;
int c2 = 0;
a = 0;
int number2[16] = {};

//converting inputy from decimal to binary

 while (inputy != 0){
    i = i+1;
    d1 = inputy % 2;
    inputy = inputy / 2;
    c2++;
    number2[c2]=d1;
    }//end while

//since the binary array is in reverse, this loop fixes it


 for(a = 0; a < c2; a = a + 1 ){
    y[a] = number2[c2-a];      
   // printf("%d", y[a]); //printf just for testing 
 }//end for

Any help is appreciated!

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • This seems like a good time to [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). To help you with debugging, I also suggest that you [break the program down into smaller and simpler parts](https://ericlippert.com/2014/03/21/find-a-simpler-problem/). – Some programmer dude Sep 14 '18 at 06:42
  • Also, don't copy-paste code in your programs. Create functions to handle common code. – Some programmer dude Sep 14 '18 at 06:42
  • I assume you're using a C++ (I don't know this language) compiler because your code has invalid C construct(s) (I noticed empty initializer list). If you're in fact using C++, update the tags; if you're using C, check your compiler settings. Also turn on all warnings and mind them. – pmg Sep 14 '18 at 06:56
  • @pmg If you mean e.g. `int x[16] = {};` then it might be a compiler-extension to allow it. – Some programmer dude Sep 14 '18 at 07:05
  • Yep @Someprogrammerdude, `int x[16] = {};` is invalid C. – pmg Sep 14 '18 at 07:08

0 Answers0