読者です 読者をやめる 読者になる 読者になる

プログラミング言語 C 問 2.3

c k&r


Cを勉強する必要が出てきたので、再勉強。

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<assert.h>

static int htoi (char *s);
static void test_htoi(void);

int
main(int argc, char **argv)
{
     int answer;

     if (argc != 2) {
          fprintf(stderr, "Invalid argument number\n");
          exit(1);
     }

     test_htoi();
     answer = htoi(argv[1]);

     printf("%s = %d\n", argv[1], answer);

     return 0;
}

static void
test_htoi()
{
     assert(htoi("0") == 0);
     assert(htoi("1") == 1);
     assert(htoi("0x0") == 0);
     assert(htoi("0x01") == 0x1);
     assert(htoi("0xa") == 0xa);
     assert(htoi("0xb") == 0xb);
     assert(htoi("0xc") == 0xc);
     assert(htoi("0xd") == 0xd);
     assert(htoi("0xe") == 0xe);
     assert(htoi("0xf") == 0xf);
     assert(htoi("0xA") == 0xA);
     assert(htoi("0xB") == 0xB);
     assert(htoi("0xC") == 0xC);
     assert(htoi("0xD") == 0xD);
     assert(htoi("0xE") == 0xE);
     assert(htoi("0xF") == 0xF);
     assert(htoi("0XF") == 0XF);
     assert(htoi("0XFF") == 0xFF);
     assert(htoi("0XFFF") == 0XFFF);
     assert(htoi("0XFFFF") == 0XFFFF);
     assert(htoi("0XFFFFF") == 0XFFFFF);
     assert(htoi("0XFFFFFF") == 0xFFFFFF);
     assert(htoi("0XFFFFFFF") == 0xFFFFFFF);
}

static int
htoi (char *s)
{
     int base;
     int index;

     int sum, num, tmp;

     sum = 0;

     base = 10;  /* decimal number */
     index = 0;

     if (s[0] == '0' && tolower(s[1]) == 'x') {
          base = 16; /* hex decimal */
          index = 2;
     }

     while (s[index] != '\0') {
          tmp = tolower(s[index]);

          if (tmp >= 'a' && tmp <= 'f') {
               num = tmp - 'a' + 10;
          }
          else if (tmp >= '0' && tmp <= '9'){
               num = tmp - '0';
          }
          else {
               return sum; /* find invalid character */
          }

          sum = (sum * base) + num;
          index++;
     }