C 語言實例 - 二進位與十進位相互轉換
二進位轉與十進位相互轉換。
實例 - 二進位轉換為十進位
#include <stdio.h>
#include <math.h>
int convertBinaryToDecimal(long long n);
int main()
{
long long n;
printf("輸入一個二進位數: ");
scanf("%lld", &n);
printf("二進位數 %lld 轉換為十進位為 %d", n, convertBinaryToDecimal(n));
return 0;
}
int convertBinaryToDecimal(long long n)
{
int decimalNumber = 0, i = 0, remainder;
while (n!=0)
{
remainder = n%10;
n /= 10;
decimalNumber += remainder*pow(2,i);
++i;
}
return decimalNumber;
}
輸出結果為:
輸入一個二進位數: 110110111 二進位數 110110111 轉換為十進位為 439
實例 - 十進位轉換為二進位
#include <stdio.h>
#include <math.h>
long long convertDecimalToBinary(int n);
int main()
{
int n;
printf("輸入一個十進位數: ");
scanf("%d", &n);
printf("十進位數 %d 轉換為二進位位 %lld", n, convertDecimalToBinary(n));
return 0;
}
long long convertDecimalToBinary(int n)
{
long long binaryNumber = 0;
int remainder, i = 1, step = 1;
while (n!=0)
{
remainder = n%2;
printf("Step %d: %d/2, 餘數 = %d, 商 = %d\n", step++, n, remainder, n/2);
n /= 2;
binaryNumber += remainder*i;
i *= 10;
}
return binaryNumber;
}
輸出結果為:
輸入一個十進位數: 100 Step 1: 100/2, 餘數 = 0, 商 = 50 Step 2: 50/2, 餘數 = 0, 商 = 25 Step 3: 25/2, 餘數 = 1, 商 = 12 Step 4: 12/2, 餘數 = 0, 商 = 6 Step 5: 6/2, 餘數 = 0, 商 = 3 Step 6: 3/2, 餘數 = 1, 商 = 1 Step 7: 1/2, 餘數 = 1, 商 = 0 十進位數 100 轉換為二進位位 1100100