tags:

views:

1298

answers:

3

If I have a string "12 23 34 56"

What's the easiest way to change it to "\x12 \x23 \x34 \x56"?

+2  A: 
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();
Jesse Beder
it avoid the extra space, just prepend a "\x" before you start and change the line in the while to be: out << " \x" << val;
Evan Teran
though from his comments, it looks like he wants a string with chars 0x12, 0x34, 0x56, 0x78 not a string containing "\x12 \x34 \x56 \x78".
Evan Teran
You mean "\\x"
Martin York
Whoops, I just noticed that; thanks for the edit, Evan.
Jesse Beder
A: 

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.

Klathzazt
+2  A: 

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.

Evan Teran