十進制轉換爲十六進制,也就是 採用 除k取餘法 ,直接讓10處以16,再對 數據如果小於10和大於10進行處理,代碼如下:
#include<iostream>
#include<string>
using namespace std;
int main()
{
long a;//輸入的數
int y=0;//循環中的餘數
string s="";//輸出的結果
cin>>a;
if(a==0)//0比較特殊,單獨處理
{
cout<<0;
return 0;
}
while(a>0)//大於0的數
{
y=a%16; //求餘
if(y<10) //小於10的餘數
s=char('0'+y)+s; //利用字符的ascll碼在字符串前面拼接
else
s=char('A'-10+y)+s; //大於9的餘數用ABCDE表示
a=a/16;
}
cout<<s;
return 0;
}
十六進制轉換爲10進制,採取的是 乘以16
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
int main()
{
string s;
int i=0,count,sum;
while(getline(cin,s))
{
int count=s.length();
sum=0;
for(i=count-1;i>=0;i--)//從十六進制個位開始,每位都轉換成十進制
{
if(s[i]>='0'&&s[i]<='9')//數字字符的轉換
{
sum+=(s[i]-48)*pow(16,count-i-1);
}
else if(s[i]>='A'&&s[i]<='F')//字母字符的轉換
{
sum+=(s[i]-55)*pow(16,count-i-1);
}
}
cout<<sum;
}
}
十進制 轉換爲 二進制,採取的是 除2取餘法,其中把 2 換成其他小於10的數,可以變成相應的 其他進制
#include<iostream>
using namespace std;
int main(){
int a;
cin>>a;
int result=0;
int temp=a;
int j=1;
while(temp){
result=result+j*(temp%2);
temp=temp/2;
j=j*10;
}
cout<<result<<endl;
return 0;
}