Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any char to hexadecimal function for C?

Tags:

c

hex

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!

like image 251
VGe0rge Avatar asked Mar 16 '10 14:03

VGe0rge


2 Answers

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);
like image 85
John Bode Avatar answered Oct 01 '22 13:10

John Bode


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);
like image 25
EvilTeach Avatar answered Oct 01 '22 13:10

EvilTeach