C ++从字符串化字节转换字节数组

时间:2014-03-25 23:49:07

标签: c++ winapi

我有一个非常大的字符串,如下所示:

std :: string tmpString =" 0xC7,0x04,0x33,0xC0,0x49,0x74,0x0A,..."

我想将每个字符串化的字节强制转换回一个字节数组。 什么是这种情况的最佳解决方案?

我使用的是VC ++

2 个答案:

答案 0 :(得分:2)

试试这个:

std::string tmpString = "0xC7,0x04,0x33,0xC0,0x49,0x74,0x0A,...";
...
std::vector<BYTE> bytes;
bytes.reserve((tmpString.length() / 5) + 1);
std::istringstream iss(tmpString);
std::string s;
while (std::getline(iss, s, ',')) {
    WORD num; // istreamstream does not have an '>>' operator for bytes
    std::istringstream(s) >> std::hex >> num;
    bytes.push_back(BYTE(num));
}

答案 1 :(得分:0)

std::string str = ("0xC7,0x04,0x33,0xC0,0x49,0x74,0x0A");
char *p2str = str.c_str();
std::vector<BYTE> numVect;
char *p2c;
do
   int num = strtol(p2str,&p2c,16);
   p2str = p2c + 1; // skiping the ,
   numVect.push_back(BYTE(num));
while(*p2c);