二进制转十六进制
string binToHex(string bin){string hex="";if(bin.size()%4!=0){for(int i=0;i<(4-bin.size()%4);i++){bin="0"+bin;}}for(int i=0;i<bin.size();i+=4){string tmp=bin.substr(i,4);bitset<4>b(tmp);hex+=b.to_ulong()<10?char(b.to_ulong()+'0'):char(b.to_ulong()+'A'-10);}return hex;
}
十六进制转二进制
string hexToBin(string hex){bitset<8>s(stoi(hex,nullptr,16));return s.to_string();
}
测试demo
#include <iostream>
#include<sstream>
#include<cstring>
#include<cctype>
#include<bitset>
using namespace std;string binToHex(string bin){string hex="";if(bin.size()%4!=0){for(int i=0;i<(4-bin.size()%4);i++){bin="0"+bin;}}for(int i=0;i<bin.size();i+=4){string tmp=bin.substr(i,4);bitset<4>b(tmp);hex+=b.to_ulong()<10?char(b.to_ulong()+'0'):char(b.to_ulong()+'A'-10);}return hex;
}string hexToBin(string hex){bitset<8>s(stoi(hex,nullptr,16));return s.to_string();
}
int main() {string str="FF";cout<<"hex is : "<<str<<endl;cout<<"hexToBin: ";cout<<hexToBin(str)<<endl;cout<<"binToHex: ";cout<<binToHex(hexToBin(str))<<endl;return 0;
}
运行结果
十进制转二进制
long long decToBin(int dec){long long res = 0, j = 1;while(dec){res = res + j * (dec % 2);dec = dec / 2;j = j * 10;}return res;
}
二进制转十进制
int binToDec(string str){int res=0;for(int i=0;i<str.size();i++){int num=str[i]-'0';res=res*2+num;}return res;
}
测试demo
#include <iostream>
#include<sstream>
#include<cstring>
#include<cctype>
using namespace std;long long decToBin(int dec){long long res = 0, j = 1;while(dec){res = res + j * (dec % 2);dec = dec / 2;j = j * 10;}return res;
}int binToDec(string str){int res=0;for(int i=0;i<str.size();i++){int num=str[i]-'0';res=res*2+num;}return res;
}
int main() {int num;while (cin >>num) { cout<<"num is : "<<num<<endl;cout<<"decToBin: ";cout<<decToBin(num)<<endl;cout<<"binToDec: ";cout<<binToDec(to_string(decToBin(num)))<<endl;}return 0;
}
测试结果