Search code examples
coctal

Printing octal literal in printf


What is the proper way to print an octal literal? For example, the following works for the hex digit \x but not for the octal \0:

printf("\x66 \0102\n");

f 2

How can this be done?


Solution

  • Octal literal consists of 1 to 3 digits. 4-digit sequence like \0102 is not supported. It seems this is treated as two characters: \010 and 2.

    What you want may be printf("\x66 \102\n");. This will print f B if ASCII is used.

    Quote from N1570 6.4.4.4 Character constants:

    octal-escape-sequence:
    \ octal-digit
    \ octal-digit octal-digit
    \ octal-digit octal-digit octal-digit

    The octal digits that follow the backslash in an octal escape sequence are taken to be part of the construction of a single character for an integer character constant or of a single wide character for a wide character constant. The numerical value of the octal integer so formed specifies the value of the desired character or wide character.