decimal to binary

This is a discussion on decimal to binary within the C Programming forums, part of the General Programming Boards category; Hi Guys Ive searched the forum but havent found much on decimal to binary so i came up with my ...

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    115

    decimal to binary

    Hi Guys
    Ive searched the forum but havent found much on decimal to binary so i came up with my own algorithm. However im encountering a seg fault and dont know where the problem lies.
    My algorithm to convert decimal to binary is:
    get the number
    find the highest power of 2
    compare the number with highest power
    if number greater the highest power print a 1
    adjust the new number
    adjust the new power
    end when there is a zero.


    Cheers

    Code:
    void dec2bin( void ) {
    {
    	int num;
    	int highestpower=1;
    	int i;
    	printf( "Enter a decimal number: " );
    	scanf( "%d", &num );
    		for ( i=1; i<=num; i++ ) {
    		if ( highestpower <= num )
    			highestpower = intpow( 2, i );
    		else if ( highestpower > num )
    			break;
    	}
    		while ( num != 0 ) {
    		if ( num >= highestpower ) {
    			putchar( '1' );
    			num = num - highestpower;
    			highestpower = highestpower - intpow( 2, sqrt(highestpower)-1);
    		}
    		else  {	
    			putchar( '0' );
    			highestpower = highestpower - intpow( 2, sqrt(highestpower)-1);
    		}
    	}
    }
    
    int intpow( int base, int power )
    {
    	if ( power == 0 )
    		return 1;
    	else
    		return base * intpow( base, power-1 );
    }
    there are only 10 people in the world, those who know binary and those who dont

  2. #2
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    why not just do something like:

    Code:
    #include <stdio.h>
    
    int main(void) {
      int i, target;
    
      printf("Enter a number: ");
      scanf("%d", &target);
    
      for(i = 32; i--;) {
        if(target & (1 << i))
          putc('1', stdout);
        else
          putc('0', stdout);
      }
    
      return 0;
    }

  3. #3
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    Code:
    #include <stdio.h>
    
    void dec2bin( int encounteredOne ) 
    {
      int theNum;
      int curBit;;
      
      printf( "Enter a number: " );
      fflush( stdout );
      scanf( "%d", &theNum );
      
      for( curBit = ( sizeof( theNum ) * 8 ) - 1; curBit >= 0; curBit-- ) {
        
        if( encounteredOne == 0 ) 
          if( theNum>>curBit & 0x01 == 0x01 ) 
    	encounteredOne = 1;
        if( encounteredOne == 1 ) {
          printf( "%d", theNum>>curBit & 0x01 );
          if( curBit % 8 == 0 ) printf( " " );
        }
        
        
      }
      
      printf( "\n" );
      
    }
    
    
    int main( ) 
    {
      dec2bin( 1 ); // use 0 if you want it to truncate it (i.e. 000101 becomes 101)
      return 0;
    }
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  4. #4
    Registered User
    Join Date
    Jun 2003
    Posts
    13
    Originally posted by master5001
    why not just do something like:

    Code:
    #include <stdio.h>
    
      for(i = 32; i--;) {
        if(target & (1 << i))
          putc('1', stdout);
        else
          putc('0', stdout);
      }
    Infact u can reduce the no of iterations of for loop:
    Code:
    #include<math.h>
    int j;
    
    j = log10(target)/log10(2); /*gives no of bits required to store target*/
    for(i=(j-1);i--;){
    if(target & (1 << i))
          putc('1', stdout);
        else
          putc('0', stdout);
      }

  5. #5
    Registered User
    Join Date
    Mar 2003
    Posts
    143
    Slight correction... to get no. bits required to store target you need:
    Code:
    j = log10(target) / log10(2) + 1;
    and you are trying to be a bit to clever with your for-loop. This version gives the right answer:
    Code:
      for(i=(j-1);i >= 0; i--)
      /* or 'for(i=j;i--; )' would also work but is a bit too cryptic for me to get my head round */
      {
        if(target & (1 << i))
          putc('1', stdout);
        else
          putc('0', stdout);
      }
    DavT
    -----------------------------------------------

  6. #6
    Registered User
    Join Date
    Jan 2003
    Posts
    115
    thanks guys for the replies.

    but just unsure how a number gets converted to binary
    for example the decimal number is 20 which is 010100 in binary. How does the bitwise recognise the decimal number 20 and convert it?

    the code you have written shifts from the left so does that start with the 0 in the decimal number 20?

    if so then its 0 & 0 = 0
    then it goes to 2, 2 & 0 = ??

    im unsure of what is taking place
    cheers
    there are only 10 people in the world, those who know binary and those who dont

  7. #7
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    All numbers, in the computer, are always in binary. There is no other possible way to store data in a computer. So the decimal literal 20 will be converted into the appropriate binary sequence by the compiler.

    Decimal, octal, hexadecimal, etc. are only different ways to represent the numbers, the underlying physical system understands binary and only binary.

  8. #8
    Registered User
    Join Date
    Jan 2003
    Posts
    115
    hmm so the moment i enter a decimal number its converted to binary already?

    so then just use bitwise operaters and compare and print out the values?

    is that the logic here?
    there are only 10 people in the world, those who know binary and those who dont

  9. #9
    Registered User
    Join Date
    Oct 2002
    Posts
    32

    Talking Bitwise is your friend

    Yep, bitwise is the way to go...and here you go for 32-bit binary!!!
    Code:
    #include <stdio.h>
    /*------------------------------------------------------------*/
    /* Decimal to binary conversion */
    
    void Decimal_2_Binary(unsigned int x, unsigned int c[32])
    {
    	int bit;		
    
    	for(bit = 0; bit < 32; bit++)
    	{
    		c[bit] = ((x >> bit) & 1);
    	}
    }
    
    
    /*------------------------------------------------------------*/
    
    int main()
    {
        int bit;
        unsigned int x;
        unsigned int c[32];		
    
    	
        printf("\nEnter an integer number smaller than 4,294,967,295: ");
        scanf("%u", &x);
        printf("\nConverting decimal to binary:\n");
    
        Decimal_2_Binary(x, c);
    
        printf("	Binary == ");
    
        for(bit = 31; bit >= 0; bit--)
        {
    	if(bit == 27 || bit == 23 || bit == 19 || bit == 15 || bit == 11 || bit == 7 || bit == 3)
    	{
    		printf(" ");
    	}
    
    
    	printf("%u", c[bit]);
        }
    
    	printf("\n\n\n");
    	return 0;
    }
    Last edited by Zalbik; 07-10-2003 at 11:30 AM.

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, 03:52 AM
  2. Confused by expression.
    By Hulag in forum C Programming
    Replies: 3
    Last Post: 04-07-2005, 07: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, 03:00 PM
  4. binary to decimal
    By miryellis in forum C Programming
    Replies: 7
    Last Post: 03-14-2004, 07:35 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

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