Hi Vivek,
 
Do you mean you require the generalized Decimal-to-binary code - meaning real numbers included - in that case :|
 
void printBinary( unsigned long num, bool firstTime )
{
    if( num == 0 )
    {
          if( firstTime == true )
                 printf("0\n");
          return;
    }
    else
    {
          printBinary( num/2, false );
          printf("%d", num%2);
    }
}
 
void printRealBin( double decimal )
{
    unsigned long intPart;
    double decPart;
     int digsAfterDec = 10;
 
    if( decimal < 0 )
    {
       printf("-");
       decimal = -decimal;
    }
    
     intPart = (unsigned long) decimal;
     decPart = decimal - intPart;
 
    /*  print the integer portion */
     printBinary( intPart, true );
 
     if( decPart <= 0.0000001 ) return;
 
     printf(".");
    /* print the fractional portion */
    while( (digsAfterDec-- > 0) && ( decPart>0 ) )
     {
            if( (decPart *= 2) >= 1 )
            {
                     printf("1");
                     decPart -= 1;
            }
            else
                     printf("0");
     }
}
 
 
:wq
mayur
 
 
---
Switch to vim  'cause it's v.i.
 
On 12/14/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


[EMAIL PROTECTED] wrote:
> iota from the C stlib.h

How is iota going to help him?  I'm guessing you had a typo for itoa,
but even that that is just converting his decimal number to a char*.

To convert decimal to binary you divide the number by two and print the
remainder. However, this will be in reverse order, which is why the
first response said to use a stack to reorder it.

int myInt = 21;

while (myInt > 0) {

    printf("%d", myInt % 2);
    myInt /= 2;
}

That will print the decimal value of 21 in binary (reverse order,)  so
instead of printing it push it onto a stack, then print out the stack
after you finish pushing the values.


Reply via email to