I have a char array with data from a text file and I need to convert it to hexadecimal format. Is there such a function for C language.
Thank you in advance!
If I understand the question correctly (no guarantees there), you have a text string representing a number in decimal format ("1234"), and you want to convert it to a string in hexadecimal format ("4d2").
Assuming that's correct, your best bet will be to convert the input string to an integer using either sscanf()
or strtol()
, then use sprintf()
with the %x
conversion specifier to write the hex version to another string:
char text[] = "1234";
char result[SIZE]; // where SIZE is big enough to hold any converted value
int val;
val = (int) strtol(text, NULL, 0); // error checking omitted for brevity
sprintf(result, "%x", val);
I am assuming that you want to be able to display the hex values of individual byes in your array, sort of like the output of a dump command. This is a method of displaying one byte from that array.
The leading zero on the format is needed to guarantee consistent width on output. You can upper or lower case the X, to get upper or lower case representations. I recommend treating them as unsigned, so there is no confusion about sign bits.
unsigned char c = 0x41;
printf("%02X", c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With