(C语言)各种进制转换(10->8 8->10 2->16)

2016-12-02 12:52:35来源:网络收集作者:Alex Lee人点击

第七城市
10->8#include
#include
#define maxnum 30
//十进制转八进制
int main(void) {
char dec[maxnum];
int oct,index,temp;
scanf("%d",&oct);
for(index=maxnum-1;index>=0 && oct>0;index--) {
temp = oct % 8;
dec[index] = temp+'0';
oct /= 8;
}

for(int i=index+1;i printf("%c",dec[i]);
}
}

8->10


#include
#include
#include
#define maxnum 30
//八进制转十进制
int main(void) {
char oct[maxnum];
int ten = 0,temp;
scanf("%s",&oct);
int len = strlen(oct);

for(int i=len-1,ind = 0;i>=0;i--,ind++) {
temp = int(oct[i]-'0')* pow(8,ind);
ten += temp;
}
printf("%d",ten);
}

8->16


#include
#include
#include
#define maxnum 30
char binTo16(char c[],int low,int high);
int binPow(int pow);
int main(void) {
char bin[maxnum];
char hex[maxnum];
gets(bin);
int len = strlen(bin)-1,edge = maxnum-1;
while(len>0) {
hex[edge] = binTo16(bin,(len-3<0?0:len-3),len);
len -= 4;
edge--;
}
for(int i=edge+1;i printf("%c",hex[i]);
}
}
char binTo16(char c[],int low,int high) {
int len = high-low+1;
int hex = 0;
char bin[5];

if(len==3) {
bin[4] = '/0';
bin[3] = c[high];
bin[2] = c[high-1];
bin[1] = c[high-2];
bin[0] = '0';
} else if(len==2) {
bin[4] = '/0';
bin[3] = c[high];
bin[2] = c[high-1];
bin[1] = '0';
bin[0] = '0';
} else if(len==1) {
bin[4] = '/0';
bin[3] = c[high];
bin[2] = '0';
bin[1] = '0';
bin[0] = '0';
} else {
bin[4] = '/0';
bin[3] = c[high];
bin[2] = c[high-1];
bin[1] = c[high-2];
bin[0] = c[high-3];
}
for(int i=3;i>=0;i--) {
int temp = (int)(bin[i]-'0') * binPow(3-i);
hex += temp;
}
return hex>9? hex-10+'A':hex+'0';
}
int binPow(int pow) {
if(pow==0) return 1;
return 2*binPow(pow-1);
}
第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台