十六进制字符串转换为二进制字符串,二进制字符串转换为十进制字符串
看某华为面试题目有感,十六进制转换为二进制很简单,同理八进制,四进制转换为二进制亦很简单。
参考网上代码,二进制转换为十进制亦很简单,不过这想法真的是很巧妙,学习到了。
//十六进制转换为二进制 string HexToBin(string& str) { string res; size_t i, len = str.length(); if (len <= 0) return res; for (i = 0; i < len; i++) { if (str[i] == '0') res += "0000"; else if (str[i] == '1') res += "0001"; else if (str[i] == '1') res += "0001"; else if (str[i] == '2') res += "0010"; else if (str[i] == '3') res += "0011"; else if (str[i] == '4') res += "0100"; else if (str[i] == '5') res += "0101"; else if (str[i] == '6') res += "0110"; else if (str[i] == '7') res += "0111"; else if (str[i] == '8') res += "1000"; else if (str[i] == '9') res += "1001"; else if (str[i] == 'a') res += "1010"; else if (str[i] == 'b') res += "1011"; else if (str[i] == 'c') res += "1100"; else if (str[i] == 'd') res += "1101"; else if (str[i] == 'e') res += "1110"; else if (str[i] == 'f') res += "1111"; else { cout << "--ERROR--" << endl; break; } } return res; } //进制转换中间变量 struct TBigInt { int len; char value[10000]; TBigInt() :len(0) { for (size_t i = 0; i < 10000; i++) value[i] = 0; } }; void AddBit(TBigInt& data, char BitVal) { size_t i = 0, len = data.len; for (i = 0; i < len; i++) { data.value[i] *= 2; } data.value[0] += BitVal; for (i = 0; i < len; i++) { data.value[i + 1] += data.value[i] / 10; data.value[i] %= 10; } if (data.value[data.len]) ++data.len; } string OutputIntStr(TBigInt& data) { int i; string res; if (0 == data.len) { res.push_back('\0'); } else { for (i = data.len - 1; i >= 0; --i) { res.push_back(data.value[i] + '0'); } } return res; } //二进制字符串转换为十进制字符串 string Bin2Deci(const string& str) { size_t i; TBigInt data; for (i = 0; i < str.length(); i++) { AddBit(data, str[i] == '1' ? 1 : 0); } return OutputIntStr(data); } int main() { int pos; string str, res; getline(cin, str); res = HexToBin(str); for (size_t i = 0; i < res.length(); i++) { if (res[i] != '0') { pos = i; break; } } res = res.substr(pos); cout << str << "->" << res << endl; cout << res << "->" << Bin2Deci(res) << endl; system("pause"); return 0; }