-
Decimal to Hex Converter
hey , im trying to create a dec to hex converter and the same formula works for all other bases but for hex i cant get it to display the letters 'a' - 'f' , if i use "%c" , i cant get the numbers to work!..please help.
Code:
int convertHex(int num)
{
quotient=(num / 16);
remainder=(num % 16);
if (remainder <= 9 && quotient >= 1)
{
b[j++]=remainder;
count++;
convertHex(quotient);
}
else if(remainder > 9 && quotient >= 1)
{
b[j++]=(((remainder-10)+'A'));
count++;
convertHex(quotient);
}
else if(quotient <= 0)
{
(remainder <= 9 ) ? (b[j++]=remainder) : (b[j++]=(((remainder-10)+'A')));
count++;
//reverse(a,count);
for (j = 0; j < count; ++j)
{
printf("%d",b[j]);
}
printf("\n");
b[bits];
count = 0;
for (j = 0; j < count; ++j)
{
b[j] = 0;
}
return b[0];
}
}
int *reverse(int *swap,int b)
{
int a = 0;
int temp;
for(a ; a < --b ; a++)
{
temp=swap[a];
swap[a]=swap[b];
swap[b]=temp;
}
return swap;
}
ive got a function which uses just printf instead of arrays however i cant reverse the digits in that ,
Code:
int convertHex(int num)
{
quotient=(num / 16);
remainder=(num % 16);
if (remainder <= 9 && quotient >= 1)
{
printf("%d",remainder);
convertHex(quotient);
}
else if(remainder > 9 && quotient >= 1)
{
printf("%c",((remainder-10)+'A'));
convertHex(quotient);
}
else if(quotient <= 0)
{
(remainder <= 9 ) ? printf("%d",remainder): printf("%c",((remainder-10)+'A'));
printf("\n");
return 0;
}
}
either one is fine , just as long as it works!..thanks !!
-
Because int x=0x7a really is the same number as int y=122, the only meaningful "hex conversion" that can take place with C integers involves realizing them as a string for some purpose.
Code:
#include <stdio.h>
int main() {
int x=0x7a, y=122, hex, dec;
printf( "Convert hex to dec: %d\n",x);
printf( "Convert dec to hex: %x\nNow input a decimal number:",y);
scanf("%d",&dec);
printf("convert to hex: %x\nInput a hexadecimal number:",dec);
scanf("%x",&hex);
printf("convert to dec: %d\n",hex);
}
I hope this simplifies things for you.