I am learning C. After completing the common core part. I found this unique program which will allow the user to create his own format specifier which will use "%b" as format specifier to convert a integer directly into binary.
I want to know more about this code.
How it works and how i can modify it.
Please Help me.
#include <stdarg.h>
void MyPrintf( char *fmt, ... )
{
va_list aptr; /* Points to each unscanned arg in turn */
char *p, *sval, str[17];
int ival;
double dval;
va_start( aptr, fmt ); /* Initialize the argument pointer. */
/* Retrieve each argument in the variable list... */
for( p=fmt; *p ; ++p )
if( *p=='%' )
switch( * ++p )
{
case 'd':
ival = va_arg( aptr, int );
printf( "%d", ival );
break;
case 'f':
dval = va_arg( aptr, double );
printf( "%f", dval );
break;
case 's':
for( sval=va_arg(aptr, char*); *sval; ++sval )
putchar( *sval );
break;
case 'b': /* for binary */
ival = va_arg(aptr, int); /* Get it as integer */
/* radix should be 2 for binary in itoa... */
itoa( ival, str, 2 );
31
32 A to Z of C
for( sval=str; *sval; ++sval )
putchar(*sval);
break;
default:
putchar(*p);
}
else
putchar( *p );
va_end( aptr ); /* Clean up when done */
} /*--MyPrintf( )----------*/
int main( void )
{
MyPrintf( "7 in binary is %b \n", 7 );
return(0);
} /*--main( )-----*/