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

Viewed 255109

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".

7 Answers

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;
}
Related