BCD码和HEX16进制码相互转换
hex_to_dec
dec_to_hex
#include<iostream> #include<string> #include<math.h> #include<sstream> using namespace std; int hex_to_dec(string hex_data){ string bin_data=""; for(int i=0;i<hex_data.length();i++){ switch(hex_data[i]){ case '0': bin_data += "0000"; break; case '1': bin_data += "0001"; break; case '2': bin_data += "0010"; break; case '3': bin_data += "0011"; break; case '4': bin_data += "0100"; break; case '5': bin_data += "0101"; break; case '6': bin_data += "0110"; break; case '7': bin_data += "0111"; break; case '8': bin_data += "1000"; break; case '9': bin_data += "1001"; break; case 'A': case 'a': bin_data += "1010"; break; case 'B': case 'b': bin_data += "1011"; break; case 'C': case 'c': bin_data += "1100"; break; case 'd': case 'D': bin_data += "1101"; break; case 'e': case 'E': bin_data += "1110"; break; case 'f': case 'F': bin_data += "1111"; break; default:break; } } int dec_data=0; int con=0; for(int j=bin_data.size()-1;j>0;j--){ if(bin_data[j]=='1'){ dec_data+=pow(2,con); } con++; } return dec_data; } string dec_to_hex(int dec_data){ string hex_data=""; while(dec_data!=0){ switch(dec_data%16){ case 0: hex_data += "0"; break; case 1: hex_data += "1"; break; case 2: hex_data += "2"; break; case 3: hex_data += "3"; break; case 4: hex_data += "4"; break; case 5: hex_data += "5"; break; case 6: hex_data += "6"; break; case 7: hex_data += "7"; break; case 8: hex_data += "8"; break; case 9: hex_data += "9"; break; case 10: hex_data +="A"; break; case 11: hex_data +="B"; break; case 12: hex_data +="C"; break; case 13: hex_data +="D"; break; case 14: hex_data +="E"; break; case 15: hex_data +="F"; break; default:break; } dec_data/=16; } string real_hex_data="0x"; for(int i=0;i<hex_data.length();i++){ real_hex_data+=hex_data[hex_data.length()-1-i]; } return real_hex_data; } string bcd_to_hex16(string bcd_data){ int dec_data; string real_bcd_data=""; for(int i=2;i<bcd_data.length();i++){ real_bcd_data+=bcd_data[i]; } istringstream is(real_bcd_data); is>>dec_data; string hex_data=dec_to_hex(dec_data); return hex_data; } string bcd_to_hex10(int bcd_data){ string hex_data=dec_to_hex(bcd_data); string real_hex_data; for(int i=2;i<hex_data.length();i++){ real_hex_data+=hex_data[i]; } istringstream is(real_hex_data); int dec_data; is>>dec_data; string hex_data2=dec_to_hex(dec_data); return hex_data2; } int main(){ string hex_data="3F"; int dec_data=hex_to_dec(hex_data); ostringstream os; os << dec_data; string dec_data1=os.str(); cout<<"16进制数:"<<hex_data<<endl; cout<<"10进制数:"<<dec_data<<endl; string bcd_data16="0x"+os.str();//用十六进制表达 int bcd_data10=hex_to_dec(dec_data1);//用十进制表达 cout<<"BCD数,用16进制表达"<<bcd_data16<<endl; cout<<"BCD数,用10进制表达"<<bcd_data10<<endl; cout<<"------------------------------"<<endl; cout<<dec_to_hex(19)<<endl; cout<<"BCD数,用16进制表达为0x63"<<endl; cout<<"BCD数,用10进制表达为99"<<endl; cout<<bcd_to_hex16("0x63")<<endl; cout<<bcd_to_hex10(99)<<endl; return 0; }