演習3-5 K&R プログラミング言語C

演習3-5

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

#define MAX 1024

void itob(unsigned n, char s[], int b);
void reverse(char s[]);

int main(int argc, char *argv[])
{
    char str1[MAX];
    char str2[MAX];
    char str3[MAX];
    unsigned n;

    n = 158;
    itob(n, str1, 2);
    itob(n, str2, 8);
    itob(n, str3, 16);
    printf("itob(158, s, 2)  => %s\n", str1);
    printf("itob(158, s, 8)  => %s\n", str2);
    printf("itob(158, s, 16) => %s\n", str3);

    return 0;
}

void itob(unsigned n, char s[], int b)
{
    int i, c;

    i = 0;
    do {
        c = n % b;
        if (c < 10) {
            s[i++] = c + '0';
        } else {
            s[i++] = c + 'A' - 10;
        }
    } while ((n /= b) > 0);
    s[i] = '
#include <stdio.h>
#include <string.h>

#define MAX 1024

void itob(unsigned n, char s[], int b);
void reverse(char s[]);

int main(int argc, char *argv[])
{
    char str1[MAX];
    char str2[MAX];
    char str3[MAX];
    unsigned n;

    n = 158;
    itob(n, str1, 2);
    itob(n, str2, 8);
    itob(n, str3, 16);
    printf("itob(158, s, 2)  => %s\n", str1);
    printf("itob(158, s, 8)  => %s\n", str2);
    printf("itob(158, s, 16) => %s\n", str3);

    return 0;
}

void itob(unsigned n, char s[], int b)
{
    int i, c;

    i = 0;
    do {
        c = n % b;
        if (c < 10) {
            s[i++] = c + '0';
        } else {
            s[i++] = c + 'A' - 10;
        }
    } while ((n /= b) > 0);
    s[i] = '\0';
    reverse(s);
}

/* 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;
    }
}
'
; reverse(s); } /* 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; } }

実行結果

$ ./ex3-5
itob(158, s, 2)  => 10011110
itob(158, s, 8)  => 236
itob(158, s, 16) => 9E
プログラミング言語C 第2版 ANSI規格準拠
B.W. カーニハン D.M. リッチー
共立出版
売り上げランキング: 9726
«
»