いくつかの間違いはありましたが、ほとんどそこにいたので、コードを「改善」しました。1 回だけ実行する必要があるベースの無限ループ テスト。while()
ループは完全に整理されていませんでした -数字x/b
抽出ループの外で行われています。私が行ったもう 1 つの変更は、ルックアップ配列を使用して各数字を文字に変換することでした。これにより、面倒なテストが大幅に削減されました。また、関数値として渡された文字列も返しました。もう少し機能を追加することもできます。不適切なベース値を渡した場合NULL
、空の文字列の代わりに返された可能性があります。また、インデックスとして使用する同じステートメントで更新j
することにも注意してください。これにより、コードがもう少し流暢になります。
#include <stdio.h>
char *base_conversion (char *s, int x, int b) {
char charr[] = "0123456789ABCDEF";
int i, j = 0, len, digit, neg = 0;
*s = 0; // terminate the string passed
if (b < 2 || b > 16) // check the base
return s; // return an empty string
if (x < 0) {
x = -x; // adjust for negative input
neg = 1;
}
do {
digit = x % b; // extract each l.s. digit
s[j++] = charr [digit]; // convert to character
} while (x /= b); // implicitly test for 0
if (neg) // negative input
s[j++] = '-'; // append a minus sign
s[j] = 0; // terminate the string
// reverse the string
len = j;
for (i=0; i<len/2; i++) {
digit = s[i];
s[i] = s[--j]; // pre-decrement j to next char index
s[j] = digit;
}
return s;
}
int main () {
int n;
char strig[65];
for (n=1000; n>=-1000; n-=2000) {
printf ("Binary %d: %s\n", n, base_conversion (strig, n, 2));
printf ("Ternary %d: %s\n", n, base_conversion (strig, n, 3));
printf ("Octal %d: %s\n", n, base_conversion (strig, n, 8));
printf ("Decimal %d: %s\n", n, base_conversion (strig, n, 10));
printf ("Hexadecimal %d: %s\n", n, base_conversion (strig, n, 16));
}
return 0;
}
プログラム出力:
Binary 1000: 1111101000
Ternary 1000: 1101001
Octal 1000: 1750
Decimal 1000: 1000
Hexadecimal 1000: 3E8
Binary -1000: -1111101000
Ternary -1000: -1101001
Octal -1000: -1750
Decimal -1000: -1000
Hexadecimal -1000: -3E8