1

I want something like

 string magic(char c);

so that when I do

 std::cout << magic(c);

I get:

  • The character itself for printing ASCII characters;
  • A 2/3-letter ASCII code for other ASCII characters (e.g. "NUL", "BEL", "LF" etc.)
  • Anything reasonable when c is non-ASCII (8th bit on).

What should I use? (It doesn't have to be a function necessarily.)

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 1
    If you want the output to be printable ASCII, you need at least one printable ASCII character to be mangled/escaped into two or three printable ASCII chars. Unless you want ambiguity. –  Mar 29 '14 at 21:33
  • Do you want that to work everywhere (ebcdic computers included)? – pmg Mar 29 '14 at 21:56
  • 1
    @einpoklum: Why not write it yourself? As long it´s only ASCII (not Unicode-stuff, EBCDIC or something even stranger), the control character amount is small. Just some if-else and an array of special names like "BEL"... – deviantfan Mar 29 '14 at 21:56
  • @delnan: Not necessarily... I can tell results apart by space, or using a field width etc. – einpoklum Mar 29 '14 at 22:39
  • @pmg: No need to get crazy... :-) – einpoklum Mar 29 '14 at 22:39
  • @deviantfan: Because I want to use common library code rather than write my own, if possible. Of course I can just write it myself. – einpoklum Mar 29 '14 at 22:40
  • 1
    @einpoklum: I don´t think there is any lib function for this. – deviantfan Mar 29 '14 at 22:43
  • 1
    Could you use a simple look-up table? `const char *magic[] = {"NUL", "SOH" ... "a", "b" ... "0xFE", "0xFF" };`. – Petr Vepřek Mar 29 '14 at 22:45
  • Simplest would be to copy the implementation of `od -t a` ("named character") from whatever source code (GNU coreutils, BSD, AST) has the copyright you like best. The names of ASCII codes can be found on the [od man page](http://pubs.opengroup.org/onlinepubs/009696799/utilities/od.html). In GNU coreutils, the appropriate function is `print_named_ascii()` in `src/od.c`. – Mark Plotnick Mar 30 '14 at 00:19

1 Answers1

1

Combining @Pter and @deviantfan's comments:

There's apparently no common library functionality for achieving this. A simple implementation would involve a lookup table for the low ASCII value, and a check for the 8th bit; an even simpler implementation would involve a lookup table for all 256 values.

einpoklum
  • 118,144
  • 57
  • 340
  • 684