tags:

views:

149

answers:

3

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!

+2  A: 

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 );
mctylr
What is the 'atoi()' doing? If c is '`char c;`' (as is conventional, when it isn't '`int c;`', which is appropriate for I/O from `getc()` etc), the code won't compile.
Jonathan Leffler
From the original question, _"I have a char array"_, so `c` is a `char*` pointer to a character. I'll make that clearer. Thanks.
mctylr
Thanks for your help:)
+3  A: 

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);
EvilTeach
The question specifies _I have a char array with data from a text file_. A char array in C is typically a C string of text, from the text file.
mctylr
Thanks for your help:)
+4  A: 

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);
John Bode
+1 for good alternate interpretation of the question, and reasonable answer.
EvilTeach
Thanks for your help :)