1 #include <iostream> 2 #include <string> 3 #include <stdint.h> 4 5 using namespace std; 6 7 string BinToHex(const string &strBin, bool bIsUpper = false) 8 { 9 string strHex; 10 strHex.resize(strBin.size() * 2); 11 for (size_t i = 0; i < strBin.size(); i++) 12 { 13 uint8_t cTemp = strBin[i]; 14 for (size_t j = 0; j < 2; j++) 15 { 16 uint8_t cCur = (cTemp & 0x0f); 17 if (cCur < 10) 18 { 19 cCur += '0'; 20 } 21 else 22 { 23 cCur += ((bIsUpper ? 'A' : 'a') - 10); 24 } 25 strHex[2 * i + 1 - j] = cCur; 26 cTemp >>= 4; 27 } 28 } 29 30 return strHex; 31 } 32 33 string HexToBin(const string &strHex) 34 { 35 if (strHex.size() % 2 != 0) 36 { 37 return ""; 38 } 39 40 string strBin; 41 strBin.resize(strHex.size() / 2); 42 for (size_t i = 0; i < strBin.size(); i++) 43 { 44 uint8_t cTemp = 0; 45 for (size_t j = 0; j < 2; j++) 46 { 47 char cCur = strHex[2 * i + j]; 48 if (cCur >= '0' && cCur <= '9') 49 { 50 cTemp = (cTemp << 4) + (cCur - '0'); 51 } 52 else if (cCur >= 'a' && cCur <= 'f') 53 { 54 cTemp = (cTemp << 4) + (cCur - 'a' + 10); 55 } 56 else if (cCur >= 'A' && cCur <= 'F') 57 { 58 cTemp = (cTemp << 4) + (cCur - 'A' + 10); 59 } 60 else 61 { 62 return ""; 63 } 64 } 65 strBin[i] = cTemp; 66 } 67 68 return strBin; 69 } 70 71 int main() 72 { 73 string strBin = "!@#$%^&*()_+~`1234567890-="; 74 string strHex = "21402324255E262A28295F2B7E60313233343536373839302D3D"; 75 76 string strBinToHex = BinToHex(strBin); 77 cout << strBinToHex << endl; 78 strBinToHex = BinToHex(strBin, true); 79 cout << strBinToHex << endl; 80 81 string strHexToBin = HexToBin(strHex); 82 cout << strHexToBin << endl; 83 84 return 0; 85 }