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 wh
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.
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.
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.
The translation is done at compile-time so that every string you manually enter into the source code with \x
and such ends up being the character it represents in the binary. If you want to do this at run-time you will need to invoke a parse function like strtol()
using base 16 passing the string containing the hex and cast it to a char.