将std :: string转换为unsigned char *并返回?
的代码是什么?str = "1234567891234567"
unsigned char* unsignedStr = ConvertStrToUnsignedCharPointer(str);
str1 = ConvertUnsignedCharToStr(unsignedStr);
str
和str1
必须相同且不会损失精确度。
答案 0 :(得分:5)
auto str1 = std::string{"1234567891234567"}; // start with string
auto chrs = str.c_str(); // get constant char* from string
auto str2 = std::string{ chrs }; // make string from char*
无符号字符*:
auto uchrs = reinterpret_cast<unsigned char*>(const_cast<char*>(chrs));
使用向量而不是原始指针:
using namespace std;
auto str1 = string{"1234567891234567"};
vector<char> chars{ begin(str1), end(str1) };
vector<unsigned char> uchars;
transform(begin(str1), end(str1), back_inserter(uchars),
[](char c) { return reinterpret_cast<unsigned char>(c); });