bitflags - How to format flags in c? -
assume there flag definitions such as:
shf_write 0x1 shf_alloc 0x2 shf_execinstr 0x4 shf_maskproc 0xf0000000 given flag, need output shf_write|shf_alloc if bits 0x1 , 0x2 on.
how trick in c?
just create character buffer enough space hold possible combinations of strings , add appropriate strings each applicable bit set. (or ditch buffer , write straight stdout, choice) here's naive implementation of how such thing:
void print_flags(int flag) { #define buflen (9+9+13+12+3+1) /* text, pipes , null terminator*/ #define pairlen 4 static struct { int value; const char *string; } pair[] = { { shf_write, "shf_write" }, { shf_alloc, "shf_alloc" }, { shf_execinstr, "shf_execinstr" }, { shf_maskproc, "shf_maskproc" }, }; char buf[buflen]; /* declare buffer */ char *write = buf; /* , "write" pointer */ int i; (i = 0; < pairlen; i++) { if ((flag & pair[i].value) == pair[i].value) /* if flag set... */ { size_t written = write - buf; write += _snprintf(write, buflen-written, "%s%s", written > 0 ? "|" : "", pair[i].string); /* write buffer */ } } if (write != buf) /* if of flags set... */ { *write = '\0'; /* null terminate (just in case) */ printf("(%s)", buf); /* print out buffer */ } #undef pairlen #undef buflen }
Comments
Post a Comment