#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct
{
char b1:1;
char b2:1;
char b3:1;
char b4:1;
char b5:1;
char b6:1;
char b7:1;
char b8:1;
}bit_t;
typedef union
{
int dnum;
char cnum[4];
}char_t;
char* CharToBinary(char num)
{
bit_t *bit;
bit=(bit_t*)#
char strnum[17]={0};
sprintf(strnum,"%d%d%d%d%d%d%d%d\n",
bit->b8,bit->b7,bit->b6,bit->b5,
bit->b4,bit->b3,bit->b2,bit->b1);
char *bnum=(char*)malloc(10);
for(int j=0,i=0;i<17;i++)
{
if(strnum[i]==0)
break;
if(strnum[i]!='-')
bnum[j++]=strnum[i];
if(j==4)
bnum[j++]=' ';
}
bnum[9]=' ';
return bnum;
}
int BinaryToInt(char *s)
{
char_t num;
int len=strlen(s)-1;
for(int i=len/8;i>=0;i--)
{
bit_t *bit;
bit=(bit_t*)&num.cnum[i];
int index=len-i*8;
bit->b1=index<0?0:(s[index--]-'0'==0?0:1);
bit->b2=index<0?0:(s[index--]-'0'==0?0:1);
bit->b3=index<0?0:(s[index--]-'0'==0?0:1);
bit->b4=index<0?0:(s[index--]-'0'==0?0:1);
bit->b5=index<0?0:(s[index--]-'0'==0?0:1);
bit->b6=index<0?0:(s[index--]-'0'==0?0:1);
bit->b7=index<0?0:(s[index--]-'0'==0?0:1);
bit->b8=index<0?0:(s[index--]-'0'==0?0:1);
}
return num.dnum;
}
int main(int argc,char**argv)
{
if(argc!=3)
{
puts("请输入参数 \n\t-b\t十进制转换为二进制\n\t-d\t二进制转换为10进制");
return 0;
}
if(!strcmp(argv[1],"-b"))
{
char_t num;
num.dnum=atoi(argv[2]);
printf("十进制为 %d\n二进制为 ",num.dnum);
char ret[33]={0};
char flag=0;
for(int i=3;i>=0;i--)
if(num.cnum[i]!=0||flag)
{
flag=1; //防止256之类的数字跳过
char *p=CharToBinary(num.cnum[i]);
printf("%s",p);
free(p);
}
puts("");
return 0;
}
else if(!strcmp(argv[1],"-d"))
{
printf("二进制为 %s\n十进制为 %d\n",argv[2],BinaryToInt(argv[2]));
return 0;
}
else
puts("参数错误,输入程序名可查看帮助");
return 0;
}