c - 如何在c中格式化标志?

标签 c bitflags

假设有如下标志定义:

SHF_WRITE     0x1
SHF_ALLOC     0x2
SHF_EXECINSTR 0x4
SHF_MASKPROC  0xf0000000

给定一个标志,如果位 0x10x2 打开,我需要输出 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/

相关文章:

c# - 无法在枚举上使用 FlagsAttribute (无法解析符号 'HasFlag' )

c++ - 在 C++ 中表示位标志的枚举中的 ALL 标志的紧凑非重复方式

c - C 中的位操作和标志测试

c - 具有特殊按位运算的宏的目的是什么?

c - 分配多维数组和不兼容的类型

c - 优雅地(即最终合作地)暂停线程执行

c - 允许管道读取碎片消息

c - 程序集:从 C 调用或作为独立程序创建时的数据段

用于保存二进制标志的 C++ 位图

powerapps - 如何检查 PowerApps 中是否设置了某个位?