演習 3-5

無職の間にK&Rを再読。演習問題の解答をさらす。解く順番は適当。

演習 3-5
符号なし整数 nb進文字表現に変換し、s に格納する(itoa と同様な)関数 itob(n, s, b) を書け。とくに itob(n, s, 16)ns 中の16進文字に変換する。


Excersize 3-5
Write the function itob(n, s, b) that converts the integer n into a base b character representation in the string s. In particular, itob(n, s, 16) formats n as a hexadecimal integer in s.


意味無く 64進数まで対応させてみた。最後の2文字はかなり無理やり。

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

void reverse(char s[]);

/* Answer */
void itob(unsigned n, char s[], int b)
{
  static char c[] = "0123456789"
                    "abcdefghijklmnopqrstuvwxyz"
                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                    "$@";
  int i = 0;
  if (2 <= b && b < sizeof(c)) {
    for (; n; n /= b)
      s[i++] = c[n % b];
  }
  s[i] = '\0';
  
  reverse(s);
}

void reverse(char s[])
{
  int c, i, j;
  
  for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
    c = s[i];
    s[i] = s[j];
    s[j] = c;
  }
}

int main(void)
{
  char s[100];
  
  unsigned n = 0xD66BB;
  
  itob(n, s, 16);
  printf(" %x \n[%s]\n", n, s);
  
  itob(n, s, 8);
  printf(" %o \n[%s]\n", n, s);
  
  itob(n, s, 10);
  printf(" %u \n[%s]\n", n, s);
  
  itob(n, s, 36);
  printf("[%s]\n", s);
  
  return 0;
}