gpt4 book ai didi

c++ - 从 C++ 字符串转换为 unsigned char* 并返回

转载 作者:搜寻专家 更新时间:2023-10-31 00:31:42 25 4
gpt4 key购买 nike

将 std::string 转换为 unsigned char* 并返回的代码是什么?

str = "1234567891234567"
unsigned char* unsignedStr = ConvertStrToUnsignedCharPointer(str);
str1 = ConvertUnsignedCharToStr(unsignedStr);

strstr1 必须相同且不会丢失精度。

最佳答案

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));

使用 vector 代替原始指针:

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); });

关于c++ - 从 C++ 字符串转换为 unsigned char* 并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33523286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com