Wednesday, October 24, 2007

Interesting C Program -17

Hey!!!
This code converts the decimal number into binary, decimal, octal and hexadecimal number systems. Here "pow()" function is used. Since pow() function returns float, the values are typecasted.
Note: Never use a^b for "a raised to the power of b". This will do the EXOR operation.
Try using pow(base,power) function.


#include "stdio.h"
#include "math.h"
/*----------#defines starts here----------*/
#define DECIMAL 10
#define BINARY 2
#define OCTAL 8
#define HEXADECIMAL 16
#define DIGITS_DECIMAL 5
#define DIGITS_BINARY 16
#define DIGITS_OCTAL 3
#define DIGITS_HEXADECIMAL 3
/*-----------#defines ends here-----------*/
/* FUNCTION DECLARATIONS STARTS HERE */
char *tobinary(int x);
char *todecimal(int x);
char *tooctal(int x);
char *tohexadecimal(int x);
/* FUNCTION DECLARATIONS ENDS HERE */
int main()
{
int x;
char *y;
printf("ENTER THE VALUE TO CONVERT:\t\t");
scanf("%d",&x);
y=tobinary(x);
printf("\nBINARY:\t\t%c %c %c %c %c %c %c %c %c %c %c %c %c %c %c %c"\
,y[0],y[1],y[2],y[3],y[4],y[5],y[6],y[7],y[8],y[9],y[10],\
y[11],y[12],y[13],y[14],y[15]);
y=todecimal(x);
printf("\nDECIMAL:\t%c %c %c %c %c",y[0],y[1],y[2],y[3],y[4]);
y=tooctal(x);
printf("\nOCTAL:\t\t%c %c %c",y[0],y[1],y[2]);
y=tohexadecimal(x);
printf("\nHEXADECIMAL:\t%c %c %c",y[0],y[1],y[2]);

return 0;
}
/* FUNCTION DEFINITIONS STARTS HERE */
char *todecimal(int x)
{
char y[3];
int i;
for(i=0;i<DIGITS_DECIMAL;i++)
{
y[i] = ((x/(int)pow(DECIMAL,(DIGITS_DECIMAL-i-1)))%DECIMAL)+0x30;
}
return y;
}

char *tobinary(int x)
{
char y[8];
int i;
for(i=0;i<DIGITS_BINARY;i++)
{
y[i] = ((x/(int)pow(BINARY,(DIGITS_BINARY-i-1)))%BINARY)+0x30;
}
return y;
}
char *tooctal(int x)
{
char y[3];
int i;
for(i=0;i<DIGITS_OCTAL;i++)
{
y[i] = ((x/(int)pow(OCTAL,(DIGITS_OCTAL-i-1)))%OCTAL)+0x30;
}
return y;
}
char *tohexadecimal(int x)
{
char y[3];
int i;
for(i=0;i<DIGITS_HEXADECIMAL;i++)
{
y[i] = ((x/(int)pow(HEXADECIMAL,(DIGITS_HEXADECIMAL-i-1)))%HEXADECIMAL)+0x30;
if(y[i]==0x3A) y[i] =0x41;
if(y[i]==0x3B) y[i] =0x42;
if(y[i]==0x3C) y[i] =0x43;
if(y[i]==0x3D) y[i] =0x44;
if(y[i]==0x3E) y[i] =0x45;
if(y[i]==0x3F) y[i] =0x46;


}
return y;
}
/* FUNCTION DEFINITIONS ENDS HERE */

2 comments:

Anonymous said...

Hi balaji,

Parts of the code are invisible. Please do the needful to benefit the reader.

Balaji V said...

Will Do that ASAP...
Thanks for the comment...

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language