drankinatty

ASCII Chart - 4 Column Char, Dec, Oct, Hex - POSIX printf

Mar 13th, 2022 (edited)
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. /*
  2.  * ISO C does not support POSIX %n$ operand number formats, but a nice twist
  3.  * with POSIX printf conversion (will generate expected -Wformat warning).
  4.  *
  5.  * (for pure standard C, see "ASCII Chart - 4 Column Char, Dec, Oct, Hex")
  6.  */
  7.  
  8. #include <stdio.h>
  9.  
  10. enum { TWO = 1u << 1, R1 = 1u << 5, R2 = 1u << 6, R3 = R1 + R2 };
  11.  
  12. #define HDG "Char  Dec  Oct  Hex"
  13. #define SEP "-------------------------------------------"
  14. #define FMT "%-5s %3d %04o 0x%02x"
  15.  
  16. int main (void) {
  17.  
  18.     /* non-printing characters */
  19.     char *special[] = { "(nul)", "(soh)", "(stx)", "(etx)",
  20.                         "(eot)", "(enq)", "(ack)", "(bel)",
  21.                         "(bs)",  "(ht)",  "(nl)",  "(vt)",
  22.                         "(np)",  "(cr)",  "(so)",  "(si)",
  23.                         "(dle)", "(dc1)", "(dc2)", "(dc3)",
  24.                         "(dc4)", "(nak)", "(syn)", "(etb)",
  25.                         "(can)", "(em)",  "(sub)", "(esc)",
  26.                         "(fs)",  "(gs)",  "(rs)",  "(us)",
  27.                         "(sp)",  "(del)" };
  28.  
  29.     /* print heading (with non-ISO C %n$ conversion specifiers) */
  30.     printf ("%1$s | %1$s | %1$s | %1$s\n%2$s%3$s\n", HDG, SEP, 1+SEP);
  31.    
  32.     /* print chars */
  33.     for (unsigned i = 0; i < R1; i++) {
  34.         char s1[TWO] = { (char)i+R1, 0 },
  35.              s2[TWO] = { (char)i+R2, 0 },
  36.              s3[TWO] = { (char)i+R3, 0 };
  37.  
  38.         printf (FMT " | " FMT " | " FMT " | " FMT "\n",
  39.                 special[i], i, i, i,
  40.                 i ? s1 : special[R1], i+R1, i+R1, i+R1,
  41.                 s2, i+R2, i+R2, i+R2,
  42.                 i == R1 - 1 ? special[R1+1] : s3, i+R3, i+R3, i+R3);
  43.     }
  44.  
  45.     return 0;
  46. }
  47.  
Add Comment
Please, Sign In to add comment