converting decimal to binary in C - Page 2

# Thread: converting decimal to binary in C

1. base 2 --&gt; 10 = value 2
base 10 --&gt; 10 = value 10
base 16 --&gt; 10 = value 16

is this what you mean?

2. No, I was attempting to illustrate why you would need the three parameters. Namely because for some cases it would be impossible to tell which of the three the original number was and for all cases AFAIK, it would be impossible to tell whether the number was hex or decimal. Not knowing this could give you a completely wrong answer.

The point I was making was that my question was not answerable by just selecting a,b or c.

What hypronix was saying was:

Design a program which, when taking a number (x) as input, changes it to base y; where x is in base z.

So you have three numbers: the number, the original base, and the base that you want to convert it to. For example, let's say the number is 12, the base is 10 and the base you want to convert it to is 2. (So from what I said above, x=12, y=2 and z=10).

You know that 12 is a decimal number from what I've just said above and you want to convert it to binary. I believe what hypronix was saying is that you should be able to design a process that can do the conversion no matter what base the original number is in and no matter what base you want to convert it to.

I'm really sorry if you don't understand what I just said there. I was just trying to explain what hypronix said without repeating exactly what he said.

ac

3. Well, this story i completely understand, i just thought he meant to create a function like
hexa(x,y)
{
/*convert decimal to hex*/
}
so you should create one function per base, i didn't understand he meant one function, which is able to convert
base2 --&gt; base10
base10 --&gt; base2
base2--&gt;base16
base16--&gt;base2
base16--&gt;base10
base10 --&gt; base16

cause i do understand you should need 3 vars for THIS
_________________________________________________________________________________________________________________
**EDIT**

well, i've just written a program which asks for a decimal input, and prints the binary value, here's the source:
#include <stdio.h>

main()
{
int a,i,c,b[8];
printf("\nEnter a decimal value: ");
scanf("%d",&a);
b[0]=a%2;
c=0;
i=1;

while(i<=7)
{
b[i]=b[c]%2;
c++;
i++;
}
printf("\nThe value of %d is ",a);
for(i=7;i>=0;i--)
printf("%d",b[i]);
printf(" in binary.\n");
}
only problem: it doesn't work!!
i can't think of anything that could be wrong (don't look at the way it is written with c++,I++ etc, since i just did this to make it more clear), it should as far as i can see, but it only prints 11111111 or 00000000, regardless of what value you give it, that means, 45 is 111111111 and 44 is 000000000, it just does the first modules....

any hints ?

**EDIT**

4. The first thing that I notice is your while loop condition. While I couldn't really say that it's not correct, it is possible that it could cause your program to go through more calculations than it needs to. A way round it is to have a var which holds your number which you divide by 2 each time. If you do that you can change the while to "while(myvar&gt;0) ..."

That isn't what's causing the problem you're describing, though.

Your problem is in your while loop. You have a logic error in the statement "b[i]=b[c]%2;"

Assuming the number to convert is 10, i=1, c=0, and b[c]=0 (10%2=0) your statement reads:

b[1]=b[0]%2; or b[1]=0%2.

0%2 is 0. If the number you enter is even you will get all zeros, if the number is odd, you will get all ones.

I'm sure you'll be able to fix it now. And BTW, don't get discouraged or anything, and don't think that it was a stupid mistake. The first thing that I noticed when I looked at your program was that statement, except that what I was thinking at first was "nicely done". I didn't notice the error and I thought you had managed to find a neat way of doing it without dividing the number by two. Just to let you know that sometimes you just miss these things. You'd probably have looked at your program a while later and it would have stuck out at you.

ac

5. at first i used "for(;i&lt;=7; )"
but i thought the while loop looks more pretty...

as for the loop itself, yes its really strange i didn't saw that, but i'll try and fix it and post the new source (have to reboot to slackware first )

thanks for your help

__________________________________________________

Well, i solved it.
this is the new source code:
#include <stdio.h>

main()
{
int a,i,c,b[8];
printf("\nEnter a decimal value: ");
scanf("%d",&a);
c=a;
for(i=0;i<=7;i++)
{
b[i]=c%2;
c=c/2;
}

printf("\nThe value of %d is ",a);
for(i=7;i>=0;i--)
printf("%d",b[i]);
printf(" in binary.\n");
}
this is the only way i can solve it, but at least it works

now for the function from one base to the other, this is gonna take some time, and first question comes up is:

how can i create a function which has as input binary or hex, how can i let the program decide if the input is binary or hex or decimal?

this is gonna be a tough problem, i'm sure of that...

6. Just for your interest, here's a program I wrote last night to convert decimal to binary. It lets you specify the number of bits that you want to use (that's kinda pointless really, but I felt like putting it in for a change :P) I'm just posting this to let you see what I was meaning about the while loop.

Note that I used cout in my code. That's just a c++ object that works similar to printf. Just ignore it and the "using namespace std;" bit at the top. It's the other code that should be of interest. Also, note that I attempted to use meaningful variable names; you need to try not to call your variables "a", "b", "c", etc.

Code:
```#include &lt;iostream&gt;
#include &lt;math.h&gt;
#include &lt;stdlib.h&gt;

using namespace std;

int main(int argc, char **argv)
{
int number = 0;
int bits   = 0;
int count  = 0;

if(argc&lt;3)
{
cout &lt;&lt; "Usage: " &lt;&lt; argv[0] &lt;&lt; " [number] [bits]\n" &lt;&lt; endl;
cout &lt;&lt; "number - the number to be converted" &lt;&lt; endl;
cout &lt;&lt; "bits   - the number of bits to be used" &lt;&lt; endl;
return(0);
}

// the next two lines take strings as input and convert them to integers
// for more info on argv[2], etc. look for a tutorial on command line parameter passing
bits   = atoi(argv[2]);
number = atoi(argv[1]);

int orignum = number; // create a copy of the original number for the end

// you can pretty much ignore this bit, but if you're interested, there's a note at the
// end of the post.
if((pow((double)2,(double)bits)-1)&lt;number)
{
cout &lt;&lt; "ERROR: too few bits used to display number." &lt;&lt; endl;
return(0);
}

int binarray[bits];

for(int x=0; x&lt;bits; x++)
binarray[x] = 0; // just making sure binarray is initialised to 0

while(number!=0) // keep looping until we cannot do any more calculations
{
binarray[count] = number % 2;
number=number/2;

count++;
}

cout &lt;&lt; orignum &lt;&lt; " is ";

for(int x=(bits-1); x&gt;=0; x--) // output binarray backwards
cout &lt;&lt; binarray[x];

cout &lt;&lt; " in binary" &lt;&lt; endl;

return(0);
}```
Hope that's of some interest to you.

ac

NOTE: double pow(double x, double y) is a method that takes a double x, raises it to the power double y and returns the answer as a double. If you do a "man pow" on your slackware box you'll get a list of all the different pow functions.

If you know your binary, you'll understand that the maximum number that 4 bits can store is (2^4)-1 (note that 2^4 takes 5 fingers to count because we count the zero :P) so that means that with 4 bits, the highest number that you can store is 15.[/edit]

7. the reason i didn't use "while(number!=0)" is because i wasn't sure if it would print the final 0;

and as for the pow and atoi functions, i did read about them a couple of weeks ago, but don't know exaclty what they do anymore, so i'll have to refresh my memory...

but, i'm glad my code worked, and i'm definitly gonna improve it in the nearby future...

one other thing, you know the game "mastermind"?
well, i thought it would be pretty easy to code it, but man was i wrong!

everything works fine, except 2 things..[*]the input can only be read with an &lt;enter&gt; between every digit...
this means 1&lt;enter&gt;2&lt;enter&gt;3&lt;enter&gt;4&lt;enter&gt;5&lt;enter&gt;
i've tried solving this problem with getchar() (and ofcourse made ans[5] char instead of int.
doesn't work....
[*]second problem: outputting a 0 (zero) for every digit in ans[] that is not in the same place in secret[], but is in another place in secret, and at the same time, don't print a 0 twice if the digit in ans[] is only presence once in secret[] although it might be present multiple times in ans[].
and vica versa: if a digit is present once in ans[], but multiple times in secret[], then it should also print only one 0;

i think you can understand why this is a big problem to me, and i hope you can help me solve it :)

here's the source so far:
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;time.h&gt;

#define N 9

int main()
{
srand( (unsigned)time( NULL ) );
int wel,i,b,c,d,e,secret[5];
int ans[5];
printf("\nWelcome to mastermind.\n");
printf("press 1 to play, press 2 for instructions :");
scanf("%d",&wel);
if (wel==2)
{
printf("\n\nThe goal of the game is to guess the secret\n");
printf("secret code. You have 10 tries for this.\n");
printf("The code contains 5 random numbers from 0 - 9.\n");
printf("Every \'*\' you see next to your input, \n");
printf("means that you have one number correct and\n");
printf("at the right place.\n");
printf("Every \'0\' you see next to your input,\n");
printf("means that you have one number correct, but\n");
printf("not at the right place.\n");
wel=1;
}
if (wel ==1)
{
printf("\nHere we go....\n\n");

for (i = 0; i &lt;5; i++)
secret[i] = rand()%10;
for(b=0;b&lt;10;b++)
{
printf("\nEnter your guess: ");
for(c=0;c&lt;=4;c++)
{
scanf("%d",&ans[c]);
}
printf("\n");
for(c=0;c&lt;=4;c++)
printf("%d",ans[c]);
printf("\t");
e=0;
for(d=0;d&lt;=4;d++)
{
if(ans[d]==secret[e])
printf("*");
e++;
}
d=0;
for(c=0;c&lt;=4;c++)
{
if(ans[c]==secret[c])
d++;
}
if(d==5)
{
printf("\nCongratulations, you've won!\n");
return 0;
}

}
if(b==10)
{
printf("\nUnfortunately you did not make it.\n");
return 0;
}
}
}
thanks for your replies....

8. Hey man, I told you about the meaningful variable names thing. I refuse to help you with your code until you change the variables from a,b,c, etc. into something more englishlike that I can track easier. Also, add in at least one or two lines of comments.

I'll help you with it certainly, but I think that if you create a new thread with the mastermind problem as the starter you're more likely to get an answer to your problem.

ac

9. ok i can understand that

i'll start a new thread with meaningfull variable names...

10. Fair enough, if you are using loads of for loops you may need a few counters, but I would worry when you've got so many embedded for loops. It might be ok, but hrrm.

And btw --
Code:
`sprintf(&ans[c],"%d",getchar());`
Hope that helps you [/edit]

The above code would still require you to have two character arrays by which point in time it's pointless using that code. I'm feeling a bit stupid this morning :P[/edit]

ac

Page 2 of 2 First 12

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•