How does “\x” work in a String?

后端 未结 4 587
一生所求
一生所求 2021-01-02 14:06

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

相关标签:
4条回答
  • 2021-01-02 15:04

    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.

    0 讨论(0)
  • 2021-01-02 15:10

    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.

    0 讨论(0)
  • 2021-01-02 15:11

    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.

    0 讨论(0)
  • 2021-01-02 15:12

    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.

    0 讨论(0)
提交回复
热议问题