If I have a string "12 23 34 56"
What's the easiest way to change it to "\x12 \x23 \x34 \x56"?
If I have a string "12 23 34 56"
What's the easiest way to change it to "\x12 \x23 \x34 \x56"?
string s = "12 23 34 45";
stringstream str(s), out;
int val;
while(str >> val)
out << "\\x" << val << " "; // note: this puts an extra space at the very end also
// you could hack that away if you want
// here's your new string
string modified = out.str();
You can do this like so:
foreach( character in source string)
{
if
character is ' ', write ' \x' to destination string
else
write character to destination string.
}
I suggest using std::string but this can be done easily by first checking the string to count how many whitespaces and then create your new destination string to be that number x3.
You question is ambiguous, it depends on what you actually want:
if you want the result be the same as: char s[] = { 0x12, 0x34, 0x56, 0x78, '\0'}: then you could do this:
std::string s;
int val;
std::stringstream ss("12 34 56 78");
while(ss >> std::hex >> val) {
s += static_cast<char>(val);
}
after this, you can test it with this:
for(int i = 0; i < s.length(); ++i) {
printf("%02x\n", s[i] & 0xff);
}
which will print:
12
34
56
78
otherwise if you want your string to literally be "\x12 \x23 \x34 \x56" then you could do what Jesse Beder suggested.