Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Transform string into its ASCII representation

Tags:

c++

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...

like image 631
sukovanej Avatar asked Aug 11 '26 05:08

sukovanej


2 Answers

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.

like image 105
Bo Persson Avatar answered Aug 13 '26 03:08

Bo Persson


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.

like image 39
pmdj Avatar answered Aug 13 '26 05:08

pmdj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!