■ 基数変換(平成16年秋期午後問4)
#include <stdio.h>
#include <stdlib.h>
/* 基本情報 平成16年秋期午後問4 */
/* 基数変換プログラム */
#define S_MAX 32
int MToInt(int Rdx, char *Num);
char *IntToN(int Val, int Rdx);
int ToInt(char P);
char ToStr(int Q);
/* エラー表示関数 */
void Error(const char *mes)
{
printf("エラー関数:%s\n", mes);
exit(EXIT_FAILURE);
}
/* 文字列の長さを返す関数 */
int Length(const char *s)
{
int c = 0;
while (*s++ != '\0') c++;
return c;
}
/* 文字列の一部を取り出す関数 */
char Substr(char *Num, int Idx, int n)
{
/* 引数 n は使用しない */
if (Idx < 1) Error("Substr()");
return *(Num + (Idx - 1));
}
char *RadixConv(int Frdx, char *Fnum, int Trdx)
{
printf("%15s(%2d) → ", Fnum, Frdx);
if (Frdx < 2 || Frdx > 16 || Trdx < 2 || Trdx > 16)
Error("RadixConv()");
return IntToN(MToInt(Frdx, Fnum), Trdx);
}
int MToInt(int Rdx, char *Num)
{
int Idx, Val;
Val = 0;
if (Rdx < 2 || Rdx > 16) Error("MToInt()");
for (Idx = 1; Idx <= Length(Num); Idx++) {
Val = Val * Rdx + ToInt(Substr(Num, Idx, 1));
}
printf("%5u → ", Val);
return Val;
}
char *IntToN(int Val, int Rdx)
{
int Quo, Rem, i, len;
static char Tmp[S_MAX];
Quo = Val;
Tmp[0] = '\0';
len = 0;
while (Quo >= Rdx) {
Rem = Quo % Rdx;
/* Tmp ← ToStr(Rem) + Tmp */
for (i = len; i >= 0; i--) {
Tmp[i+1] = Tmp[i];
}
Tmp[0] = ToStr(Rem);
/* ----------------------- */
len++;
Quo /= Rdx;
}
/* Tmp ← ToStr(Quo) + Tmp */
for (i = len; i >= 0; i--) {
Tmp[i+1] = Tmp[i];
}
Tmp[0] = ToStr(Quo);
/* ----------------------- */
printf("%15s(%2d)\n", Tmp, Rdx);
return Tmp;
}
const char Code[] = "0123456789ABCDEF";
int ToInt(char P)
{
int Idx;
Idx = 0;
while (P > Code[Idx]) {
Idx++;
if (Idx > 15) Error("ToInt()");
}
return Idx;
}
char ToStr(int Q)
{
if (Q < 0 || Q > 15) Error("ToStr()");
return Code[Q];
}
/* テスト */
int main()
{
RadixConv(16, "00", 2);
RadixConv(16, "0F", 8);
RadixConv(16, "FFF", 2);
RadixConv(16, "FFF", 8);
RadixConv(2, "1000", 8);
RadixConv(16, "7FFF", 2);
RadixConv(2, "111111111111111", 8);
RadixConv(16, "0FFF", 10);
RadixConv(8, "377", 16);
RadixConv(10, "255", 8);
return 0;
}