I have this program that claims to convert a decimal number to hexadecimal. The issue is that the program throws the above warning and I don't know how to correct it. The return (variable identifier) is supposed to be a %s
because what you want to display is a string.
#include <stdio.h>
int main() {
int n = 0;
char hex = '\0';
const char * HEX_DIG = "0123456789ABCDEF";
printf ("Enter a positive integer: ");
scanf ("%d",&n);
do{
hex = HEX_DIG [n % 16 + 1] + hex;
n = (int) n/16;
}while ( n != 0 );
printf ("\nHexadecimal= %s", hex);
return 0;
}
The %s
format token expects to be given a string which, in C, is a pointer to a char
(or an array of char
s). You've provided it a char
which, when passed to a function with variadic arguments (in this case, printf
), gets promoted to an int
. That's what the compiler is complaining about.
Furthermore, even if your code was valid C, you'd be printing the integer backwards.
To print a char
, you need to use %c
. The best way to incorporate that into your existing code would be to move the printf
inside the loop:
for (int k=0; k<sizeof(int)*2; k++) {
hex = HEX_DIG[(n >> (sizeof(int)*8-4)) & 0xf]; // Move the high four bits all the way to the right and then mask them off.
n <<= 4; // Shift the next four bits into place.
if ( hex != '0' ) { // No need to print leading 0's.
printf("%c", hex);
}
}
printf("\n");
To explain the sizeof
calculations, let's assume that int
s are four-bytes wide. Then sizeof(int)*2
would be eight which accounts for the eight sets of four bits. sizeof(int)*8-4
would be 28 and so we'd be shifting off all 32 bits except for the four highest.
Note that this code does ignore the case when n
is zero. In such a case, the loop would print nothing.
Backing up a bit, unless you're doing this as an exercise (perhaps a homework problem), I'd recommend not reinventing the wheel as printf
already supports the printing of integers in hex format:
printf("%x\n", n);