简体   繁体   English

使用C宏构造字符串/字符转义序列

[英]Construct string/char escape sequence using C macro

I'd be looking for C macro like: CHR(0x20) which would produce string "\\x20". 我想要的是C宏:CHR(0x20),它将产生字符串“ \\ x20”。

I'm sure that's not possible. 我敢肯定那是不可能的。 Care to prove me wrong? 想证明我错了吗? ;-) ;-)

You can do this by generating a large header file, eg using a little bit of Python: 您可以通过生成一个较大的头文件来做到这一点,例如使用一些Python:

for x in range(0,256):
  print '#define BODGE_0x%x \\x%x' % (x,x)

And then use the output of that in C: 然后在C中使用该输出:

#include <stdio.h>

#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));
}

Which does exactly what you asked for, gcc -E shows: gcc -E可以完全满足您的要求:

return printf("%s\n", "\x20");

It's possible (but fiddly) to do something less crude if you accept calling CHR(20) to imply hex without the 0x prefix. 如果您接受调用CHR(20)隐含不带0x前缀的十六进制,则有可能(但很奇怪)做一些不那么粗略的事情。

The obvious solution would be to build a macro that expands to: 显而易见的解决方案是构建一个宏,扩展为:

printf("%s", "\x" "20");

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: 因此,GCC给出了错误:

error: \x used with no following hex digits

We can however work around that and cause the string "\\x20" to be generated by using a pre-processor concatenation ( ## ) in conjunction with the "usual" preprocessor stringification indirection: 但是,我们可以解决该问题,并通过结合使用“预处理器”字符串化间接调用和预处理器串联( ## )来生成字符串“ \\ x20”:

#include <stdio.h>

#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));
}

This does work and, gcc -E shows: 这确实有效,并且gcc -E显示:

return printf("%s", ("\x20"));

which is what we'd hope to see when the macro works. 这是我们希望在宏工作时看到的内容。


You could also do: 您也可以这样做:

#define CHR(x) ((char[2]){(x), 0x0})

which has the desired effect. 具有预期的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM