2013年7月15日月曜日

開発環境

プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第3章(制御の流れ)3.6(ループ (do-while))の演習3-5を解いてみる。

その他参考書籍

演習 3-5.

コード

sample.c

#include <stdio.h>
#include <string.h>
#define MAXLINE 1000

void itob(int, char s[], int);

int main()
{
    char s1[MAXLINE], s2[MAXLINE],
         s3[MAXLINE], s4[MAXLINE];
    int n;
    
    /* 2進数 1100 8進数 14 10進数 12 16進数 c */
    n = 12;
    
    itob(n, s1, 2);
    itob(n, s2, 8);
    itob(n, s3, 10);
    itob(n, s4, 16);
    printf("2進数: %s\n8進数: %s\n10進数: %s\n16進数: %s\n",
        s1, s2, s3, s4);
    return 0;
}

void itob(int n, char s[], int b)
{
    int i, m;
    void reverse(char s[]);
    
    i = 0;
    do {
        m = n % b;
        s[i++] = m < 10 ? m + '0' : m - 10 + 'a';
    } while ((n /= b) > 0);
    
    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;
    }
}

入出力結果(Terminal)

$ ./a.out
2進数: 1100
8進数: 14
10進数: 12
16進数: c
$

0 コメント:

コメントを投稿