标签:image switch code mamicode instr ima 二进制 进制 ++
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 string HexToBin(string s) //16进制转2进制 7 { 8 string str = ""; 9 for (int i = 0; i < s.size(); ++i) 10 { 11 switch (s[i]) 12 { 13 case ‘0‘: str += "0000"; break; 14 case ‘1‘: str += "0001"; break; 15 case ‘2‘: str += "0010"; break; 16 case ‘3‘: str += "0011"; break; 17 case ‘4‘: str += "0100"; break; 18 case ‘5‘: str += "0101"; break; 19 case ‘6‘: str += "0110"; break; 20 case ‘7‘: str += "0111"; break; 21 case ‘8‘: str += "1000"; break; 22 case ‘9‘: str += "1001"; break; 23 case ‘A‘: str += "1010"; break; 24 case ‘B‘: str += "1011"; break; 25 case ‘C‘: str += "1100"; break; 26 case ‘D‘: str += "1101"; break; 27 case ‘E‘: str += "1110"; break; 28 case ‘F‘: str += "1111"; break; 29 } 30 31 } 32 return str; 33 } 34 35 36 37 int main() 38 { 39 40 int n; 41 while (cin >> n) 42 { 43 string s; 44 for (int i = 0; i < n; ++i) 45 { 46 cin >> s; 47 string binStr = HexToBin(s); //先将s转换为二进制串binStr 48 int a = (int)binStr.size() % 3; 49 if (a != 0) //如果二进制串的长度不是3的倍数,就在前面补零 50 { 51 for (int i = 1; i <= 3 - a; ++i) 52 binStr = "0" + binStr; 53 } 54 55 for (int i = 0; i < binStr.size(); i += 3) 56 { 57 string str; 58 str = binStr.substr(i, 3); //截取binStr长度为3的子串 59 if (str == "000" && i != 0) 60 cout << 0; 61 else if (str == "001") 62 cout << 1; 63 else if (str == "010") 64 cout << 2; 65 else if (str == "011") 66 cout << 3; 67 else if (str == "100") 68 cout << 4; 69 else if (str == "101") 70 cout << 5; 71 else if (str == "110") 72 cout << 6; 73 else if (str == "111") 74 cout << 7; 75 } 76 cout << endl; 77 } 78 79 } 80 81 return 0; 82 83 }
标签:image switch code mamicode instr ima 二进制 进制 ++
原文地址:https://www.cnblogs.com/FengZeng666/p/10354625.html