Nosrettap
Nosrettap

Reputation: 11340

How does "\x" work in a String?

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?

Upvotes: 14

Views: 37333

Answers (4)

Robert Groves
Robert Groves

Reputation: 7748

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.

Upvotes: 3

Andreas Hagen
Andreas Hagen

Reputation: 2345

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.

Upvotes: 0

Kendall Frey
Kendall Frey

Reputation: 44374

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.

Upvotes: 7

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272687

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.

Upvotes: 11

Related Questions