Referring second answer to question: How to convert from ASCII to Hex and vice versa?
I want to save the char hex[3] equivalent of different characters as follows:
char *str ="abcd";
// I want to get hex[3] of each character in above string and save into the following:
char str2[4]; // should contain hex values as : \x61 for a,\x62 for b,\x63 for c,\x64 for d
How can I do this ?
I tried the following so far:
int i;
char ch;
char hex[3];
for(i=0; i<strlen(str);i++) {
ch = charToHex(*(str+i), hex);
// now hex contains the first and second hex characters in hex[0] & hex[1]
// I need to save them in the first index of str2
// e.g. if hex[0] = 7 and hex[1] = f, then str2[0] should be "\x7f"
// -> how do I do this part ?
}
Thanks.
You can use a
forloop to iterate over all characters of a string, and then apply the conversion for each character. Bear in mind that C strings are null-terminated.Also note that 4 characters will not be enough if you want to store
\x61\x62\x63\x64– you’ll need4 * strlen(str) + 1, i.e. 17.In response to the code:
You don’t actually need
ch. The functioncharToHexreturnvoid, i.e. nothing.Simply copy the characters to the output string, like this:
Again, don’t forget to set the null terminator in the result string.
Also, since you call
strlenin each iteration, you’re writing a Schlemiel the Painter algorithm.