プログラミング言語 C 3.5


符号なし整数 nを b進数に変換し、文字列 sに格納する関数 htob(n, s, b)を書け、
という問題。どんどん bで割っていって、余りを sに格納していって、最後に sを
反転させればいいはず。

#include <stdio.h>
#include <string.h>
#include <assert.h>

static void htob(int n, char *s, int b);
static void reverse(char *s);
static void test_htob();

int
main(void)
{
     test_htob();
}

static void
test_htob()
{
     char buf[2048];

     htob(1, buf, 2);
     assert(!strcmp(buf, "1"));

     htob(100, buf, 10);
     assert(!strcmp(buf, "100"));

     htob(64, buf, 8);
     assert(!strcmp(buf, "100"));

     htob(0xdddddd, buf, 16);
     assert(!strcmp(buf, "dddddd"));
}

static void
htob(int n, char *s, int b)
{
     int i, tmp;

     i = 0;
     while (n > 0) {
          tmp = n % b;
          s[i++] = (tmp >= 10) ? (tmp + 'a' - 10) : (tmp + '0');
          n = n / b;
     }
     s[i] = '\0';

     reverse(s);
}