C语言【进制转换】
基础知识(进制)
-
P进制x上的每一个位相对十进制而言表达的含义都不同
从右到左,各表示个位,P位,P2位,…,Pn位
pg: -
十进制-245 5为个位 4为十位 2为百位-D
-
八进制-245 5为个位 4为八位 2为64位-O
-
二进制-245 5为个位 4为二位 2为4位-B
-
十六进制:0-9+A-F–H
遵循满P进位的原则
十进制转换为其他进制
辗转相除法
十进制转换为n进制只需将上图2换为n
十进制转换为二进制
例题-和数转换二进制
#include <stdio.h>
#include <math.h>
#include <string.h>
void binary(char a[])
{
int i,l,sum=0,m,t,count=0,power;
l=strlen(a);
for(i=0;i<l;i++)
{
m=a[i]-'0';
sum+=m;
}
t=sum;
while(t!=0)
{
t/=2;
count++;
}
for(i=count-1;i>=0;i--)
{
power=(int)pow(2,i);
printf("%d",sum/power);
sum%=power;
}
}
int main()
{
char m[10];
gets(m);
binary(m);
}
十进制转为任意进制
输入两个正整数m(≤10,000)和n(2-9),n表示n进制,采用0、1、2、3、…、n-1,共n个数码,编程完成该数的n进制转换。
#include <stdio.h>
#include <math.h>
int main()
{
int m,n,t,i,count=0,power;
scanf("%d %d",&m,&n);
t=m;
while(t!=0)
{
t/=n;
count++;
}
printf("%d ",count);
for(i=count-1;i>=0;i--)
{
power=(int)pow(n,i);
printf("%d",m/power);
m%=power;
}
}
其他进制转十进制
位权相加
对其他进制数从右往左进行编号,0,1,2…
将每一位数通过【数值*基数(进制数)^编号】然后将结果相加
原理
P进制x上的每一个位相对十进制而言表达的含义都不同
从右到左,各表示个位,P位,P2位,…,Pn位
pg:
- 十进制-245 5为个位 4为十位 2为百位-D
- 八进制-245 5为个位 4为八位 2为64位-O
- 二进制-245 5为个位 4为二位 2为4位-B
- 十六进制:0-9+A-F–H
- 因此,P进制x=d1d2…dn
换个形式x = d1P^n-1 + d2P ^n-2 +…+ dn-1*P + dn
#include <stdio.h>
#include <math.h>
int main()
{
int i,a,t=0,power,count=0;
int m[10];
scanf("%d",&a);
while(a!=0)
{
a/=10;
count++;
}
for(i=0;i<count;i++)
{
m[i]=a%10;
a/=10;
}
for(i=0;i<count;i++)
{
power=pow(2,i);
t+=m[i]*power;
}
printf("%d",t);
}
八进制,十六进制与二进制相互转换:拆位
1个八进制数<=>3个二进制数
1个十六进制数<=>4个二进制数
先分组然后从右向左编号
计算与上述相同