C ++ Converts a string to its ASCII representation

I am writing a simple package parser. For testing, I have prepared data in the following format:

std::string input = "0903000000330001 ... ";

      

and I need to convert it to something like this

0x09 0x03 0x00 0x00 ...

      

Could you please help me create a new line?

I've 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

      

Am I really missing or misunderstanding something ...

+3


source to share


2 answers


std::string

can contain a string with embedded nul characters, but you must specify its length in the constructor:

std::string NewInput("\x09\x03\x00 ... ", number_of_characters);

      



Otherwise, it std::string

will use it strlen

to calculate the length and stop at \x00

.

+6


source


Strings in C and to some extent also in C ++ are null terminated. Therefore, if a character '\x00'

(aka '\0'

) is encountered , it is considered the end of the line. If you are mainly interested in the numerical values โ€‹โ€‹of each character, you can use std::vector<uint8_t>

or similar instead . std::string

can handle null characters (you need to use explicit length function overloading), but, for example, c_str()

may not work as you might expect.



+1


source







All Articles