检查某个二进制字符串是否等于十六进程表示的字符串

来源:互联网 发布:bzero windows 编辑:程序博客网 时间:2024/06/03 11:43



可以将两个字符串序列转换为10进制进行比较。


一共实现三个函数

1. 判断是否相等

2. 将2或16进制转为1进制

3. 将一个字符c转为数字



参考代码:

#include <iostream>#include <string>#include <cmath>using namespace std;// 比较bool CompareBin_Hex(const string& binary, string& hex);// 将字符转为数字static int CharToDigit(char c);// 将二进制或十六进制转为十进制static int ConvertToBase(const string& str, int base);// 比较bool CompareBin_Hex(const string& binary, string& hex){if (binary.empty() || hex.empty())return false;int n1 = ConvertToBase(binary, 2);int n2 = ConvertToBase(hex, 16);if (n1 < 0 || n2 < 0)return false;if (n1 == n2)return true;return false;}// 将二进制或十六进制转为十进制static int ConvertToBase(const string& str, int base){// 从最后一位开始算起int end = str.size() - 1;int value = 0;for (int index = end; index >= 0; index--){int num = CharToDigit(str[index]);if (num < 0 || num >= base) // num>=base 超出该进制的范围return -1;// 指数最后一位从0开始int exp = end - index;value += num * pow(base, exp);}return value;}// 将字符转为数字static int CharToDigit(char c){if (isdigit(c))return c - '0';else if (c <= 'F' && c >= 'A')return c - 'A' + 10;else if (c <= 'f' && c >= 'a')return c - 'a' + 10;return -1;}void TestComBinHex(){string bin1 = "1111";string hex1 = "F";cout << boolalpha << CompareBin_Hex(bin1, hex1) << endl; // truestring bin2 = "10101011";string hex2 = "AB";string hex3 = "QQ";cout << boolalpha << CompareBin_Hex(bin1, hex1) << endl; // truecout << boolalpha << CompareBin_Hex(bin2, hex2) << endl; // truecout << boolalpha << CompareBin_Hex(bin2, hex3) << endl; // false}int mian(){TestComBinHex();return 0;}


阅读全文
0 0
原创粉丝点击