Converting a Digit Character

Given that we have a digit character, we want to convert it to its integer equvalent (the "meaning" of the digit character). chrutil.c contains a function to do this, dig_to_int():
     /*   Function converts ch to an integer if it is a digit. Otherwise, it
          prints an error message.
     */
     int dig_to_int(char ch)
     {
          if (IS_DIGIT(ch))
               return ch - '0';
          printf("ERROR:dig_to_int:  %c is not a digit\n", ch);
          return ERROR;
     }

Why does this work?

Even though we think a digit character, say '4', as a character, the internal representation is still as a number - the ASCII code for '4'. Fortunaltely, the selection of codes for the digit characters are contiguous n the ASCII table, so to find the integer equivalent of a digit character, we can find it's distance from the beginning of the codes for digit characters, by subtraction:

so when we say:

     ch  - '0'
the code evaluates
     '4' - '0'
which the hardware sees as
      52 -  48
which is
         4

We can use the same technique to convert an integer, in the range 0-9, to a character:

     /*   Function converts a positive integer less than 10 to a corresponding
          digit character.
     */
     char int_to_dig(int n)
     {
          if (n >= 0 && n < 10)
               return n + '0';
          printf("ERROR:int_to_dig:  %d is not in the range 0 to 9\n", n);
          return NULL;
     }

when we say:
      n  + '0'
the code evaluates
      4  + '0'
which the hardware sees as
      4  +  48
which is
        52
which, as a character is:
        '4'


[up] to Overview.