English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

in C how do you convert a binary number ectered in by a user to its decimal form. Have to be done in a function and loop through the number entered to get the answer.

2006-09-25 08:02:50 · 3 answers · asked by browngod2002 1 in Computers & Internet Programming & Design

3 answers

Do your own homework (its simple).

2006-09-25 09:27:15 · answer #1 · answered by justme 7 · 0 0

Man, this sounds like a homework assignment!
I think that once you understand how to do this manually you'll find that there's no magic to programming it. Split it into two steps:

(1) read the binary in such a way that when you've reached the end of the binary number you will have its value stored in a number (long/int/short/whatever)
(2) write the number in base 10.

Step 2 is trivial, so I won't bother with that part.
Step 1 is boring. Think about how you'd read a base 10 number.
Example: 45612
That's 4*10^4 + 5*10^3 + 6*10^2 + 1*10^1 + 2*10^0. Now, if were to go through the string from left to right, one character per iteration, we could multiply by 10 each time.

Pseudocode (my C is horrible):

int myValue = 0;
string myString = "45612";
for( int i = 0 ; i < myString.length ; i++ ){
myValue = 10 * myValue + ParseInt(myString[i]);
}
printf("Decimal Value: %i",myValue);

I think that's enough guidance. If I simply write the actual code for you then you won't learn anything (even if this isn't homework).

2006-09-25 15:20:17 · answer #2 · answered by APHawkes 2 · 0 2

This is the function. Just call it with as parameter the sting entered by the user. Warning. this works only for a valid binary string.

int asciiBinaryToHex(char *input)
{
int result=0;
int charPtr=0;

while(input[charPtr]!='\0')
{
result<<=1;
if(input[charPtr]=='1')
{
result|=1;
}
charPtr++;
}

return result;
}

2006-09-25 15:13:59 · answer #3 · answered by cd4017 4 · 1 1

fedest.com, questions and answers