Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do this by generating a large header file, e.g. using a little bit of Python:</p> <pre class="lang-py prettyprint-override"><code>for x in range(0,256): print '#define BODGE_0x%x \\x%x' % (x,x) </code></pre> <p>And then use the output of that in C:</p> <pre><code>#include &lt;stdio.h&gt; #include "bodge.h" #define xstr(s) str(s) #define str(s) #s #define XCHR(x,y) (xstr(x##y)) #define CHR(x) xstr(BODGE_##x) int main() { return printf("%s\n", CHR(0x20)); } </code></pre> <p>Which does exactly what you asked for, <code>gcc -E</code> shows:</p> <pre><code>return printf("%s\n", "\x20"); </code></pre> <hr> <p>It's possible (but fiddly) to do something less crude if you accept calling <code>CHR(20)</code> to imply hex without the <code>0x</code> prefix.</p> <p>The obvious solution would be to build a macro that expands to:</p> <pre><code>printf("%s", "\x" "20"); </code></pre> <p>which is fairly easy to do with one level of indirection, and the obvious assumption would be that the compile time concatenation of strings would handle this. Unfortunately that solution isn't viable because of the point in translation when the escape sequence gets handle. GCC therefore gives the error:</p> <pre><code>error: \x used with no following hex digits </code></pre> <p>We can however work around that and cause the string "\x20" to be generated by using a pre-processor concatenation (<code>##</code>) in conjunction with the "usual" preprocessor stringification indirection:</p> <pre><code>#include &lt;stdio.h&gt; #define xstr(s) str(s) #define str(s) #s #define XCHR(x,y) (xstr(x##y)) #define CHR(y) XCHR(\x,y) int main() { return printf("%s", CHR(20)); } </code></pre> <p>This does work and, gcc -E shows:</p> <pre><code>return printf("%s", ("\x20")); </code></pre> <p>which is what we'd hope to see when the macro works.</p> <hr> <p>You could also do:</p> <pre><code>#define CHR(x) ((char[2]){(x), 0x0}) </code></pre> <p>which has the desired effect.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload