Question
4
// Standard header for printf
#include <stdio.h> // function which converts
decimel to octal
void dectooct(int a, char *ptr);
// function which converts decimel hexadecimel
void dectohex(int a, char *ptr);
// a custom function to convert modulus of integer devisions
to hexadecimel equivalents (A through F)
char convert(int num);
// When we use the devision by base algorith to convert
the number, the remiainders are chained in the
// reverse order of their occurances. So the string
so produced has to be reversed.
void reverse(char *ptr);
// main starts here.
int main()
{
// The decimel number input
int number;
// octal equivalent output
char octalstring[100];
//hexadecimel equivalent output
char hexastring[100];
// loop through, until 0 is input.
while(1)
{
printf("Enter a number (Enter 0 to quit) :");
scanf("%d", &number);
// terminating condition
if(number == 0)
return 0;
// Get the equivalent in octalstring
dectooct(number, octalstring);
//reverse the string to get the correct number
reverse(octalstring);
dectohex(number, hexastring);
reverse(hexastring);
printf("Number: %d, octal : %s (%o), hexa: %s(%x)\n",
number, octalstring, number, hexastring, number);
}
return 0;
}
void dectooct(int a, char *ptr)
{
int mod;
while(a != 0)
{
// devide by 8, the octal base.
mod = a % 8;
a = a / 8;
// populate the array. while doing this, add 48 which
is the integer equivalent of '0'.
*ptr = mod + 48;
ptr++;
}
*ptr = 0;
}
void dectohex(int a, char *ptr)
{
int mod;
while(a != 0)
{
mod = a % 16;
a = a / 16;
if(mod > 9)
*ptr = convert(mod);
else
*ptr = mod + 48;
ptr++;
}
*ptr = 0;
}
char convert(int num)
{
char a;
switch(num)
{
case 10:
a = 'A';
break;
case 11:
a = 'B';
break;
case 12:
a = 'C';
break;
case 13:
a = 'D';
break;
case 14:
a = 'E';
break;
case 15:
a = 'F';
break;
default:
a = '0';
break;
}
return a;
}
void reverse(char *ptr)
{
int i;
char c;
int length = strlen(ptr);
for(i = 0; i < (length / 2); i++)
{
c = ptr[i];
ptr[i] = ptr[length - i -1];
ptr[length - i - 1] = c;
}
}
|