进制转化
将N转化成R进制
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /*进制转换 2 将一个数n装化成R进制(2<=R<=16) 3 4 Sample Input 5 7 2 6 23 12 7 -4 3 8 9 Sample output 10 111 11 1B 12 -11 13 */ 14 #include<stdio.h> 15 int main() 16 { 17 int n,r,i,k,t; 18 char f[1000],g[18]={"0123456789ABCDEF"}; 19 while(scanf("%d%d",&n,&r)!=-1) 20 {t=0; 21 if(n<0) 22 { 23 n=-n; 24 t=1; 25 } 26 27 k=0; 28 while(n!=0) 29 { 30 f[k++]=g[n%r]; 31 n=n/r; 32 } 33 if(t==1) 34 printf("-"); 35 for(i=k-1;i>=0;i--) 36 printf("%c",f[i]); 37 printf("\n"); 38 } 39 return 0; 40 }
二进制~十六进制、八进制~十进制、十进制~八进制
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //二进制转化成十六进制 2 #include<stdio.h> 3 #include<string.h> 4 5 int main() 6 { 7 char s[100]; 8 int i,sum,f[10000]; 9 f[0]=1; 10 for(i=1;i<32;i++) 11 f[i]=f[i-1]*2; 12 scanf("%s",s); 13 strrev(s); 14 sum=0; 15 for(i=0;s[i]!='\0';i++) 16 sum=sum+(s[i]-'0')*f[i]; 17 printf("%x\n",sum); 18 return 0; 19 } 20 21 //八进制转化成十进制 22 #include<stdio.h> 23 #include<string.h> 24 int main() 25 { 26 char s[1000]; 27 int i,j,sum; 28 scanf("%s",s); 29 strrev(s); 30 sum=0;j=1; 31 for(i=0;s[i]!='\0';i++) 32 { 33 sum=sum+(s[i]-'0')*j; 34 j=j*8; 35 } 36 printf("%d\n",sum); 37 return 0; 38 } 39 //十进制转化成八进制 40 #include<stdio.h> 41 #include<string.h> 42 int main() 43 { 44 int n,k; 45 char s[1000]; 46 scanf("%d",&n); 47 k=0; 48 while(n!=0) 49 { 50 s[k++]=n%8+'0'; 51 n=n/8; 52 } 53 s[k]='\0'; 54 strrev(s); 55 puts(s); 56 return 0; 57 }