Reputation: 37
How do I create a string that contain multiple '\x41'
or with arbitrary '\xnn'
by copy from some give string for example:
char * string1 = "4141414141414141";
or char * string2 = "bde54d7ee10a2122";
And I would like my char * string3
become something like:
char * string3 = "\xbd\xe5\x4d\x7e\xe1\x0a\x21\x22";
or char * string3 = "\x41\x41\x41\x41\x41\x41\x41\x41";
Here is the code that I am trying to do, but it doesn't work.
char * string1 = "4141414141414141";
char c;
char * slash_x = "\\x";
int len = strlen(string1);
char * string3 = (char *) malloc(9);
for (i = 0; i < len; i++) {
if (0 == i % 2) {
printf("start\n");
j = i;
strcat(salt_empty, slash_x);
c = string[j];
printf("%c\n", c);
strncat(salt_empty, &c, 1);
j++;
c = string[j];
printf("%c\n", c);
strncat(salt_empty, &c, 1);
}
}
printf("%s\n", string3);
So the output with string3
will be "\x41\x41\x41\x41\x41\x41\x41\x41"
instead of "AAAAAAAA"
at console.
How could I fix the code in order to get "AAAAAAAA"
If the string1 is "bde54d7ee10a2122"
, then the string3
output at console would be ��M~
!"
Upvotes: 1
Views: 575
Reputation: 70971
You want:
char string1[] = {0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0};
Upvotes: 1
Reputation: 144989
You cannot convert the string by re-interpreting it from its source form. Use this instead (inefficient, but simple):
char *string1 = "4141414141414141";
int i, j, len = strlen(string1) & ~1;
char string3[len / 2 + 1];
for (i = j = 0; i < len; i += 2, j++) {
char buf[3];
memcpy(buf, string1 + i, 2);
buf[2] = '\0';
string3[j] = strtol(buf, NULL, 16);
}
string3[j] = '\0';
printf("%s\n", string3);
Upvotes: 3
Reputation: 32727
For each pair of characters in the source string, determine the hex value of each character in the pair, combine them to come up with the encoded character, then store the result in your destination string.
Upvotes: 0