#include<stdio.h>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<string>
using namespace std;
void main() //主函数
{printf("输入“1”:可进行十进制数转化为二进制和十六进制\n");
printf("输入“2”:可进行八位的二进制数转化为十进制和十六进制\n");
printf("输入“3”:可进行十六进制数转化为十进制和二进制\n");
printf("输入“其他”:不进行运算\n");
printf("---------------------------------------------------\n");
while(1) //使得主程序反复运行,方便多次输入
{
int num;
scanf("%d", &num);
if(num==1)
{
int ma1(int num1);
ma1(num);
}
if(num==2)
{
int z2_10(int a[]);
int a[8],i;
printf("输入八位的二进制数为:");
for(i=0;i<8;i++)
{
scanf("%1d",&a[i]);
}
printf("\n【转换为十进制数】:%d\n\r",z2_10(a));
int m = 0,s;
int n = 0;
char six[20];
s=z2_10(a);
printf("\n【转换成十六进制】:");
while (1){
six[m] = s% 16;
s/= 16;
if (s == 0)
{
break;
}
m++;
}
for (n=m; n >= 0; n--)
{
int k = six[n];
if (k >= 10)
{
printf("%c", 'A' + k - 10);
//'A'对应的ASCII码值为10
}
else
{
printf("%d", k);
}
}
printf("\n");
printf("---------------------------------------------------\n");
}
if(num==3)
{printf("\n请输入一个十六进制数:");
string s;
cin>>s;
int len=s.size();
int count=0,i;
int a[50];
long sum=0;
for(i=0;i<len;i++)
{
switch(s[i])
{
case '0': a[i]=0; break;
case '1': a[i]=1; break;
case '2': a[i]=2; break;
case '3': a[i]=3; break;
case '4': a[i]=4; break;
case '5': a[i]=5; break;
case '6': a[i]=6; break;
case '7': a[i]=7; break;
case '8': a[i]=8; break;
case '9': a[i]=9; break;
case 'A': a[i]=10; break;
case 'B': a[i]=11; break;
case 'C': a[i]=12; break;
case 'D': a[i]=13; break;
case 'E': a[i]=14; break;
case 'F': a[i]=15; break;
default: break;
}
}
for(i=len-1;i>=0;i--)
{
sum+=pow(16,count)*a[i];
count++;
}
printf("\n【转换为十进制数】:");
cout<<sum<<endl;
int num1 = 0;
int m = 0;
int j = 0;
int two[20];
num1 = sum;
while(1)
{
two[m] = num1 % 2;
num1 /= 2;
if (num1 == 0)
{
break;
}
m++;
}
printf("\n【转换成二进制】:");
for (j=m; j >= 0; j--)
{
printf("%d", two[j]);
}
printf("\n");
printf("---------------------------------------------------\n");
}
if(num!=1||num!=2||num!=3)
{printf("请选择转换模式\n");
printf("---------------------------------------------------\n");}
}
}
int ma1(int num1)//十进制转化为二进制和十六进制的函数,除以2或16取余反向输出
{
int num2 = 0;
int i = 0;
int j = 0;
int two[20];
printf("请输入一个十进制数字:");
scanf("%d", &num1);
num2 = num1;
while(1)
{
two[i] = num1 % 2;
num1 /= 2;
if (num1 == 0)
{
break;
}
i++;
}
printf("\n【转换成二进制】:");
for (j=i; j >= 0; j--)
{
printf("%d", two[j]);
}
printf("\n");
int m = 0;
int n = 0;
char six[20];
printf("\n【转换成十六进制】:");
while (1)
{
six[m] = num2 % 16;
num2/= 16;
if (num2 == 0)
{
break;
}
m++;
}
for (n=m; n >= 0; n--)
{
int k = six[n];
if (k >= 10)
{
printf("%c", 'A' + k - 10);
//'A'对应的ASCII码值为10
}
else
{
printf("%d", k);
}
}
printf("\n\n");
printf("---------------------------------------------------\n");
system("pause");
return num1;
}
int z2_10(int a[])//二进制转十进制的函数,每一位数字做2的次幂,做和
{
int power(int b);
int n,i,sum=0,term;
for(i=0,n=7;i<8;i++,n--)
if(n>=0)
{
term=a[i]*power(n);
sum=sum+term;
}
return sum;
}
int power(int b)
{
int i=2,j=1;
if(b==0) i=1;
for(;j<b;j++) i=2*i;
return i;
}