假设有如下标志定义:
SHF_WRITE 0x1
SHF_ALLOC 0x2
SHF_EXECINSTR 0x4
SHF_MASKPROC 0xf0000000
给定一个标志,如果位 0x1
和 0x2
打开,我需要输出 SHF_WRITE|SHF_ALLOC
。
如何在 C 中完成这个技巧?
最佳答案
#define V(n) { n, #n }
struct Code {
int value;
char *name;
} decode[] = {
V(SHF_WRITE),
V(SHF_ALLOC),
{ 0, NULL },
};
void f(const int x) {
struct Code *c = decode;
int beenthere = 0;
for(; c->name; ++c)
if(x & c->value)
printf("%s%s", beenthere++ ? "|" : "", c->name);
if(beenthere)
printf("\n");
}
关于c - 如何在c中格式化标志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6560986/