【华为练习题】十六进制字符串形式转为内存值形式
题目
功能:将十六进制字符串形式内容转为内存值形式(注:pBuffer的内存申请由调用者保证)
输入:szHexText:十六进制字符串形式,如: “6566”
输出:dataOutput,其中:内存值形式Buffer,即内存的{0x65, 0x66}
返回:返回转换成功的buffer的有效字节数
解答
#include <iostream>
#include <string>
using namespace std;
inline bool isRight(char c){
return (c >= ‘0‘ && c <= ‘9‘) || (c >= ‘a‘ && c <= ‘f‘) || (c >=‘A‘ && c <= ‘F‘);
}
int hexToBin(string &s){
string tmp;
for (unsigned i = 0; i < s.size(); i++)
{
if (isRight(s[i]))
{
tmp.push_back(s[i]);
}
}
s.clear();
s.push_back(‘{‘);
int count = 0;
for (unsigned i = 0; i < tmp.size() - 1; i += 2)
{
count++;
s += "0x";
s.push_back(tmp[i]);
s.push_back(tmp[i+1]);
s.push_back(‘,‘);
}
s.pop_back();
s.push_back(‘}‘);
return count;
}
时间: 2024-10-27 12:16:53