I'm writing a C/C++ program that involves putting a hex representation of a number into a string and I'm confused as to how \x
works. I've seen examples where people have written things such as "\xb2". In this case, how does the program know if you want the hex of b followed by the number 2 or if you want the hex of b2? Additionally, when it stores this into memeory does it save the "\x" characters or does it just save the hex representation?
std::string is a typedef for a particular instantiation of the std::basic_string template class. Its definition is found in the <string> header: using string = std::basic_string<char>; Thus string provides basic_string functionality for strings having elements of type char.
Most programming languages have a data type called a string, which is used for data values that are made up of ordered sequences of characters, such as "hello world". A string can contain any sequence of characters, visible or invisible, and characters may be repeated.
When you use the escape sequence \x inside a string the data following the \x is actually stored in it's binary representation.
So the string "ABC" is equivalent to the string "\x414243"
If you want to emit hexadecimal values in display-character form, you'll want to use the %x or %X format specifier character:
printf("%X%X%X", 'A', 'B', 'C'); // emits "414243"
See Section 1.2.6 and Section 1.2.7 of the C Library Reference Guide
Hope that explanation helps.
As an example, the string "123\x45"
is stored in hex as 31 32 33 45
.
As per Oli's answer, the longest valid value after the '\x' is used.
The '\x' is not stored. Any escape sequence does not store the characters you see on the screen, it stores the actual character specified. For example, '\n' is actually stored as a linefeed character, 0x0A.
From the C99 standard (6.4.4.4):
Each octal or hexadecimal escape sequence is the longest sequence of characters that can constitute the escape sequence.
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