微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C++ 字符串到字节

如何解决C++ 字符串到字节

所以我有一个这样的字符串:std::string MyString = "\\xce\\xc6";

当我像这样打印时:std::cout << MyString.c_str()[0] << std::endl;

作为输出我得到:\

我希望它是这样的:std::string MyDesiredString = "\xce\xc6";

所以当我这样做时:

std::cout << MyDesiredString.c_str()[0] << std::endl;
// OUTPUT: \xce (the whole byte)

所以基本上我想识别字符串(代表字节)并将其转换为真实字节数组

我想出了一个这样的函数

// this is a pseudo code i'm sure it has a lot of bugs and may not even work
// just for example for what i think
char str_to_bytes(const char* MyStr) { // MyStr length == 4 (\\xc6)
  std::map<char*,char> MyMap = { {"\\xce",'\xce'},{"\\xc6",'xc6'} } // and so on
  return MyMap[MyStr]
}
//if the provided char* is "\\xc6" it should return the char '\xc6'

但我相信一定有更好的方法来做到这一点。

尽管我搜索了很多,但没有找到任何有用的东西

提前致谢

解决方法

尝试这样的事情:

std::string teststr = "\\xce\\xc6";
std::string delimiter = "\\x";
size_t pos = 0;
std::string token;
std::string res;
while ((pos = teststr.find(delimiter)) != std::string::npos) {
    token = teststr.substr(pos + delimiter.length(),2);
    res.push_back((char)stol(token,nullptr,16));
    std::cout << stol(token,16) << std::endl;
    teststr.erase(pos,pos + delimiter.length() + 2);
}
std::cout << res << std::endl;

拿你的字符串,用表示十六进制的文字分割它。提供值 (\x) 然后解析两个十六进制。 Igor Tandetnik 提到的带有 stol 函数的字符。然后,您当然可以将这些字节值添加到字符串中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。