53

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

Example: The integer 50 would be converted to the hexadecimal string "32" or "0x32".

0

7 Answers 7

58

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
Sign up to request clarification or add additional context in comments.

4 Comments

I would recommend using the # modifier instead of writing your own 0x, especially with %p whose behavior is implementation-defined and might already include the 0x for you.
Might want to mention snprintf, too.
Also, the format of your answer is confusing with the alternating blocks. It may be useful to have just one code block with the results as comments after the statement.
@R.. Note that with #, the "0x" is not pre-pended when the value is 0. printf("%#X\n", 0); --> 0. IMO, printf("0x%X\n", a); is worthy, keeping the x as lower case and A-F as upper. 0x559E7C4
28

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

1 Comment

Nice, this was what I was exactly looking for. Oh I just realized this post was 10 years go, well thanks anyway.
21

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

3 Comments

You may want to at least give the signature or a link to a man page for strtol.
strtol() is the opposite of what he asked for. That goes the wrong direction.
You can use %X for an upper case output.
17

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;

}

3 Comments

missing num variable
You don't check for a base > 16. It should at least be in the header. Also, I think you can leave the sign to the caller
You have to replace variable num by n in order to make this script work.
3

I made a librairy to make Hexadecimal / Decimal conversion without the use of stdio.h. Very simple to use :

char* dechex (int dec);

This will use calloc() to to return a pointer to an hexadecimal string, this way the quantity of memory used is optimized, so don't forget to use free()

Here the link on github : https://github.com/kevmuret/libhex/

Comments

1

To convert an integer to a string also involves char array or memory management.

To handle that part for such short arrays, code could use a compound literal, since C99, to create array space, on the fly. The string is valid until the end of the block.

#define UNS_HEX_STR_SIZE ((sizeof (unsigned)*CHAR_BIT + 3)/4 + 1)
//                         compound literal v--------------------------v
#define U2HS(x) unsigned_to_hex_string((x), (char[UNS_HEX_STR_SIZE]) {0}, UNS_HEX_STR_SIZE)

char *unsigned_to_hex_string(unsigned x, char *dest, size_t size) {
  snprintf(dest, size, "%X", x);
  return dest;
}

int main(void) {
  // 3 array are formed v               v        v
  printf("%s %s %s\n", U2HS(UINT_MAX), U2HS(0), U2HS(0x12345678));
  char *hs = U2HS(rand());
  puts(hs);
  // `hs` is valid until the end of the block
}

Output

FFFFFFFF 0 12345678
5851F42D

Comments

1

This answer is for those, who need to start from string in decimal representation (not from int).

  1. Convert your string representation of the number to an integer value (you can use int atoi( const char * str ); function
  2. Once you have your integer you can print it as HEX using, for example, sprintf function with %x as a format parameter and you integer as a value parameter

Here is a working example: https://ideone.com/qIoHNW

#include <stdio.h>
 
int main(void) { 
    int n;
    char hex_val[50];
 
    n = atoi("100663296");
    sprintf(hex_val, "%x", n);
 
    printf("%s", hex_val);
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.