# Thread: help: dec to binary

1. ## help: dec to binary

This is a simple piece of code that i wrote to convert decimals to binary.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int
quotient (int n)
{
int y = floor(n/2);
return y;
}

int
main(int argc, char **argv)
{
int n = atoi(argv[1]);
while(n>0){
printf("%d", n%2);
n = quotient(n);
}
printf("\n");
return 0;
}

Now, obviously i need to reverse the output in order to get the binary equivalent. Can someone please tell me the easiest way of doing this?

Is it possible for me to put the output in an array and then reverse it?

int
main(int argc, char **argv)
{
int n = atoi(argv[1]);
while(n>0){
c[12]=n%2;
printf("%d", c[12]);
n = quotient(n);
}
printf("\n");
printf("%d", c[12]);
return 0;
}

But c[12] doesn't seem to remember the numbers. Any help appreciated. thanks.

2. Code:
```int main(int argc, char **argv)
{
int n = atoi(argv[1]);

while(n>0){
c[12]=n%2;
printf("%d", c[12]);
n = quotient(n);
}
printf("\n");
printf("%d", c[12]);
return 0;
}```
c is never defined in thie code you've given. Furthermore, c[12] is one single cell in that array. You're using the same exact variable over and over. I'm assuming you want to move through the array? As such, replace 12 with a counter variable instead. Increment or decrement it as needed.

Search the board. Converting from binary to decimal and back again is a common problem / post here.

Quzah.

3. ## Newbie

Sorry i am new as you can get. I could really use some help with this one.

My first bit of code as posted above. Gives me the answer.

All i want to do is to stick the answer into an array and then reverse it. Is there anyway i can put the output of a printf statement into an array of characters?

That seems like a really simple way to do it.

And then all i have to do is to reverse the thing to get the answer in binary.
I have no idea how to loop an array to get the answer.

4. ## final code :)

Hey this works.
Only took all day.

int
quotient(int n)
{
int y = floor(n/2);
return y;
}

void
reversearray(int *ia, int size)
{
int temp;
int left=0; right=size-1;
while(left<right){
temp = ia[left];
ia[left] = ia[right];
left++;
right--;
}
return;
}

int
main(int argc, char **argv)
{
int i;
int y=atoi(argv[1]);
int n[20];
int m = 0;
while(y>0){
n[m++] = y%2;
y = quotient(y);
}
reversearray(n, m);
for(i=0; i<m; i++){
printf("%d", n[i]);
}

printf("\n");
return 0;
}

5. Sticky: << !! Posting Code? Read this First !! >>

>>int y=atoi(argv[1]);
You should always check argc before using the argv array.

6. ## checking argc.

How do you do that?

Popular pages Recent additions