【发布时间】:2022-01-22 22:28:12
【问题描述】:
在 C# 中,我们有以下函数将字符串转换为 UTF-8 编码的字节序列,反之亦然:
Encoding.UTF8.GetString(Byte[])-
Encoding.UTF8.GetBytes(Char[])/Encoding.UTF8.GetBytes(String)
我正在尝试在 C++ 中实现相同的功能,如下所示:
std::string GetStringFromBytes(std::vector<uint8_t> bytes){
std::string str(bytes.begin(), bytes.end());
return str;
}
std::vector<uint8_t> GetBytesFromString(const std::string& str){
std::vector<uint8_t> bytes(str.begin(), str.end());
return bytes;
}
这种方法正确吗?我假设我正在转换的字符串已经是 UTF-8 格式。
【问题讨论】:
-
Is this approach correct?- 你试过并查看结果了吗? -
“正确”是什么意思?
-
std::string已经有字节,你不必复制它们,只需使用它们。你几乎没有转换任何东西,你在复制。