#include
#include
#include
#include
#include "function.h"
#define N 100
//问题1:程序实现的太啰嗦了。。。求优化或给个优化的思路。//问题2:16转n进制那块,一个函数里怎么实现输出 转成2进制,转成10进制 (一个函数里实现2个功能)int main()
{
void display();
void bin_n(char *bin_str);
void decimal_n (int integer);
void hex_n (char *hex);
int judge = 0; //judge input int decimal = 0;
char hex[N];
char binary[N];
/**************** DEFINE Variable *******************/
while (1)
{
display();
scanf ("%d",&judge);
system("clear");
switch (judge)
{
case 1:
printf ("Please Input Decimal:");
scanf ("%d", &decimal);
decimal_n(decimal);
break;
case 2:
printf ("Please Input Binary:");
scanf ("%s", binary);
bin_n(binary);
break;
case 3:
printf ("Please Input Hex:");
scanf ("%s", hex);
hex_n (hex);
break;
case 0:
break;
default:
printf ("\n\nError , Please Input Again !");
break;
}
if (judge == 0)
break;
}
return 0;
}
/************************** 上面是Main.c **************************************/
/************************** 下面是function.h************************************/
#ifndef FUNCTION_H_INCLUDED
#define FUNCTION_H_INCLUDED
#define N 100
void display ()
{
printf ("\n\n\n\n");
printf ("**************************** \n");
printf ("* \n");
printf ("* 1: Input Decimal To All \n");
printf ("* 2: Input Binary To All \n");
printf ("* 3: Input Hex To All \n");
printf ("* \n");
printf ("* 0: Input 0 Leave \n");
printf ("* \n");
printf ("*************************** \n");
printf ("\n\n");
printf ("Please Input:");
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
int square(int u, int n)
{
int sum = 1;
while (n)
{
sum *= u;
n--;
}
return sum;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void decimal_n (int integer) //将十进制数转换成2,16进制,并输出{
int *bin = calloc(N,sizeof(int));
int count = 0;
printf ("\nHex == %x\n", integer);
while (integer) //1/2=0,1%2 = 1 {
*(bin++) = integer % 2;
integer /= 2;
count++;
}
printf ("Binary ==");
while (count-- != 0)
{
printf ("%d", *--bin);
}
free (bin);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void bin_n (char *bin_str)
{
int square (int u,int n);
int d_sum = 0;
int len_bin = strlen(bin_str);
while (*bin_str != '\0')
{
if (*bin_str == '1')
{
d_sum += square (2, len_bin-1);
bin_str++;
len_bin--;
}
else
{
len_bin--;
bin_str++;
}
}
printf ("\nDecimal == %d\n", d_sum);
printf ("Hex == %x\n", d_sum);
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void hex_n (char *hex)
{
char hex_table[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char hex_bin_table[][5] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
int len_hex = strlen(hex);
int i = 0;
printf ("\nBinary ==");
while (len_hex--)
{
for (i = 0;i < 16;i++)
{
if (*hex == hex_table[i])
{
printf ("%s",hex_bin_table[i]);
break;
}
}
hex++;
}
}
#endif //FUNCTION_H_INCLUDED