Beispiel #1
0
/*
 * Take a string (char *s), which has previously been verified to contain only
 * binary characters (1 or 0), and convert it to a decimal number
 */
double binary_to_decimal( char *s )
{
    /*  Our initial variables */
    unsigned int placement = 0;
    double total = 0;

    /*  We're starting on the 'right side' of the binary string */
    int i = 0;

    //  If we're doing the big-endian thing (default)
    if( bigEndian == 1 )
    {
        for( i = strlen(s); i >= 0; --i )
        {
            /*  If we hit a newline or a null char, just ignore it */
            if( s[i] == '\n' || s[i] == '\0' )
                continue;

            if( s[i] == '0' ) { ++placement; }

            else if( s[i] == '1' )
            {
                total += power_of( 2.0f, placement );
                ++placement;
            }

        }   //  for i, etc.
    }   //  if bigEndian


    //  Otherwise, do the weird, little-endian stuff
    else
    {
        for( i = 0; i < strlen( s ); ++i )
        {
            /*  If we hit a newline or a null char, just ignore it */
            if( s[i] == '\n' || s[i] == '\0' ) continue;

            if( s[i] == '0' ) { ++placement; }

            else if( s[i] == '1' )
            {
                total += power_of( 2.0f, placement );
                ++placement;
            }

        }   //  for i, etc.
    }


    /*  Return our total */
    return( total );
}
int main(void){
  int number;
  int length;
  int first;
  int power;
  int body;
  int i;
  int length_copy;
  char num;
  number = 98;
  length_copy = number_length(number);
  /*do this for the lenght of the number*/
  for(i = 0 ; i < length_copy; i++)
  {
    length =  number_length(number);
    first = first_digit(number, length);
    /*converting an integer to a char*/
    num = first +48;
    write(1, &num, 1);
    power = power_of(length);
    body = num_body(number, power, first);
    number = body;
  }
  return 0;
}