How does "\x" work in a String?

28,457

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
28,457
Nosrettap
Author by

Nosrettap

I recently graduated from Duke University as a computer science and economics double major. I am now working full time as a software developer. I am proficient in Objective-C and Java, and I know (to some degree) C, C++, Python, Perl, SML, Assembly, HTML, CSS, JavaScript.

Updated on April 08, 2020

Comments

  • Nosrettap
    Nosrettap about 4 years

    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?

  • Nosrettap
    Nosrettap about 12 years
    And when it stores this sequence does it actually store the characters \x?
  • yakoudbz
    yakoudbz over 6 years
    I know this is almost 6 years old, but is there a way to escape that hexadecimal sequence without writing anything to the string ?? Say I want to have a string with 255 'a' 'b' 'c'. I can't write "\xffabc" and I can't write "\xff abc" because I'm adding a character.
  • yakoudbz
    yakoudbz over 6 years
    FOUND IT! I just have to use the concatenation of string and write "\xff""abc"