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 for
loop 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 need 4 * strlen(str) + 1
, ie 17.
In response to the code:
You don't actually need ch
. The function charToHex
return void
, ie nothing.
Simply copy the characters to the output string, like this:
str2[2*i] = hex[0];
str2[2*i+1] = hex[1];
Again, don't forget to set the null terminator in the result string.
Also, since you call strlen
in each iteration, you're writing a Schlemiel the Painter algorithm .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.