binary to decimal

This is a discussion on binary to decimal within the C Programming forums, part of the General Programming Boards category; I need to convert a binary number to a decimal number does this look good: Code: #include <stdio.h> int main() ...

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    6

    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;
    }
    Last edited by juancardenas; 02-19-2003 at 10:50 AM.

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>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.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need help with decimal to binary Algorithm
    By webznz in forum C Programming
    Replies: 4
    Last Post: 03-13-2008, 04:52 AM
  2. Confused by expression.
    By Hulag in forum C Programming
    Replies: 3
    Last Post: 04-07-2005, 08:52 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 04:00 PM
  4. binary to decimal
    By miryellis in forum C Programming
    Replies: 7
    Last Post: 03-14-2004, 08:35 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21