binary to decimal

• 02-19-2003
juancardenas
binary to decimal
I need to convert a binary number to a decimal number

does this look good:

Code:

``` #include <stdio.h> int main() { int digit, number = 0, binary, counter1 = 1, counter2, div = 1, mod = 10, bi = 1;         printf( "Enter a number in binary(12 max): " );         scanf( "%d", &binary );         while ( counter1 <=12 ) {                 counter2 = 1;                 while ( counter2 == 1 ) {                     digit = ( binary % mod ) / div;                     mod *= 10;                     div*= 10;                     counter2++;                 }                 number = number + digit * bi;                 bi *= 2;                 counter1++;         }         printf( "The decimal equivalent is: %d\n", number );         return 0; }```
• 02-19-2003
Hammer
>>scanf( "%d", &binary );
This will input a decimal number. So entering 11 will be eleven, not 3. This you already know, as I can see from your code. But what if the user enters something that isn't valid binary?

It might be better to read input as a string, valid it and then convert it. There are various threads on the subject on these forums, if you do a search, you can see how other have done this.