Close

Code: Printing signed integers

A project log for reprint: modern printf

reprint is printf redone with decades of hindsight, revamping the semantics and syntax to make a function worthy of Hello World.

analog-twoAnalog Two 04/01/2016 at 10:240 Comments

Here is a head to head comparison of reprintf to printf:

/* char */
char sc = -42;
printf("The answer is %hhi", sc);
reprintf("The answer is \fp", sc);

/* short */
short ss = -4242;
printf("The answer is %hi", ss);
reprint("The answer is \fq", ss);

/* int */
int si = -424242;
printf("The answer is %i", si);
reprintf("The answer is \fr", si);

Most C programmers (consciously or not) default to printing signed integers. In reprint, this is the easiest format to output as it requires only a single letter (p, q, or r) to follow \f. Namely,

  1. 'p' corresponds to "char"
  2. 'q' corresponds to "short int"
  3. 'r' corresponds to plain "int"
  4. 's' corresponds to "long int"

The reason for starting at 'p' is simply that its corresponding hex value is 0x70, putting it at the top of its column in the ASCII table. Thus if we look at the lower 3 bits of each character:

  1. 'p' & 0x7 == 0
  2. 'q' & 0x7 == 1
  3. 'r' & 0x7 == 2
  4. 's' & 0x7 == 3

There are even more integer types defined by C and referenced by characters beyond 's', but that is enough for now.

Contrast this with printf, where 'hh' is the *smallest sized integer, just a single 'h' is second smallest, no modifier is "normal" and 'l' is the bigger. Arbitrary much?

*(on some platforms char is 32 bits...and the same size as the other types.)

Discussions