簡體   English   中英

C++ 字符串轉字節

[英]C++ String to byte

所以我有一個這樣的字符串: std::string MyString = "\\xce\\xc6";

當我這樣打印它時: std::cout << MyString.c_str()[0] << std::endl;

作為 output 我得到: \

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

所以當我這樣做時:

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

所以基本上我想識別字符串(代表字節)並將其轉換為實際字節數組

我想出了一個像這樣的 function:

// 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, nullptr, 16) << std::endl;
    teststr.erase(pos, pos + delimiter.length() + 2);
}
std::cout << res << std::endl;

拿你的字符串,用表示十六進制的文字把它分開。 提供值( \x ),然后解析兩個十六進制。 正如 Igor Tandetnik 提到的,帶有stol function 的字符。 然后,您當然可以將這些字節值添加到字符串中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM