标签:十六进制转八进制 div else ring ret 1.0 space continue str
1 //十六进制转二进制,二进制转八进制 2 3 #include <iostream> 4 #include <map> 5 using namespace std; 6 7 int main() { 8 string s; //输入的十六进制 9 string binaryNum; //二进制数 10 int n; 11 cin >> n; 12 13 string str[16] = {"0000", "0001", "0010", "0011", 14 "0100", "0101", "0110", "0111", 15 "1000", "1001", "1010", "1011", 16 "1100", "1101", "1110", "1111"}; 17 18 map<string, string> m; 19 m["000"] = "0"; m["001"] = "1"; m["010"] = "2"; m["011"] = "3"; 20 m["100"] = "4"; m["101"] = "5"; m["110"] = "6"; m["111"] = "7"; 21 22 for (int i = 0; i < n; i++) 23 { 24 cin >> s; 25 int len_s = s.length(); 26 for(int j = 0; j < len_s; j++) 27 { 28 if(s[j] > ‘9‘) 29 { 30 binaryNum += str[s[j] - ‘A‘ + 10]; 31 } 32 else 33 { 34 binaryNum += str[s[j] - ‘0‘]; 35 } 36 } 37 38 int len_b = binaryNum.length(); //二进制数的长度 39 if(len_b % 3 == 1) //将二进制的长度转为3的倍数 40 { 41 binaryNum = "00" + binaryNum; 42 } 43 else if(len_b % 3 == 2) 44 { 45 binaryNum = "0" + binaryNum; 46 } 47 48 int flag = 0; //前导为0标志 49 string temp; //获取三位二进制数,将其转为八进制 50 string octalNum; //八进制数 51 for(int j = 0; j < len_b; j += 3) 52 { 53 temp = binaryNum.substr(j, 3); 54 octalNum = m[temp]; 55 if(j == 0 && octalNum == "0") //如果取出的二进制数前三位为0,则重新取接下来的3位二进制数 56 { 57 flag = 1; 58 continue; 59 } 60 if(flag == 1 && j == 3 && octalNum == "0") //如果接下来的二进制还为0,则继续取(后边取的肯定不是0) 61 { 62 continue; 63 } 64 cout << octalNum; 65 } 66 67 cout << endl; 68 binaryNum = ""; 69 } 70 71 return 0; 72 }
标签:十六进制转八进制 div else ring ret 1.0 space continue str
原文地址:http://www.cnblogs.com/cao-lei/p/7172355.html