How can I convert an integer to a hexadecimal string in C?

Solution 1:

This code

int a = 5;
printf("%x\n", a);

prints

5

This code

int a = 5; 
printf("0x%x\n", a);

prints

0x5

This code

int a = 89778116;
printf("%x\n", a);

prints

559e7c4

If you capitalize the x in the format it capitalizes the hex value:

int a = 89778116;
printf("%X\n", a);

prints

559E7C4

If you want to print pointers you use the p format specifier:

char* str = "foo";
printf("0x%p\n", str);

prints

0x01275744

Solution 2:

The following code takes an integer and makes a string out of it in hex format:

int  num = 32424;
char hex[5];

sprintf(hex, "%x", num);
puts(hex);

gives

7ea8

Solution 3:

Usually with printf (or one of its cousins) using the %x format specifier.

Solution 4:

Interesting that these answers utilize printf like it is a given. printf converts the integer to a Hexadecimal string value.

//*************************************************************
// void prntnum(unsigned long n, int base, char sign, char *outbuf)
// unsigned long num = number to be printed
// int base        = number base for conversion;  decimal=10,hex=16
// char sign       = signed or unsigned output
// char *outbuf   = buffer to hold the output number
//*************************************************************

void prntnum(unsigned long n, int base, char sign, char *outbuf)
{

    int i = 12;
    int j = 0;

    do{
        outbuf[i] = "0123456789ABCDEF"[num % base];
        i--;
        n = num/base;
    }while( num > 0);

    if(sign != ' '){
        outbuf[0] = sign;
        ++j;
    }

    while( ++i < 13){
       outbuf[j++] = outbuf[i];
    }

    outbuf[j] = 0;

}