开发者

Is there any char to hexadecimal function for C?

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 开发者_StackOverflow社区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);


You can use atoi and sprintf / snprintf. Here's a simple example.

char* c = "23";
int number = atoi(c);
snprintf( buf, sizeof(buf), "%x", number );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜