I'm writing a simple packet parser. For testing, I've prepared data in format as followed:
std::string input = "0903000000330001 ... ";
and I need to transform it into something like this
0x09 0x03 0x00 0x00 ...
Could you help me how I should construct the new string?
I already tried these ...
std::string newInput = "\x09\x03\x00 ... ";
std::string newInput = "\u0009\u0003\u0000 ...";
but the program returns that the size of this string is only two.
std::cout << newInput.size() << std::endl;
> 2
I'm really missing or misunderstanding something...
std::string can hold a string with embedded nul characters, but you have to tell its length in the constructor:
std::string NewInput("\x09\x03\x00 ... ", number_of_characters);
Otherwise, std::string will use strlen to compute the length, and stop at the \x00.
Strings in C, and to some extent also in C++, are terminated with the null character. So if the '\x00' (aka '\0') character is encountered, that's taken to be the end of the string. If you're mainly interested in the numerical values of each character, you may want to use a std::vector<uint8_t> or similar instead. std::string can handle null characters (you need to use the function overloads with explicit lengths) but for example c_str() may not behave as you might expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With