C++中如何将字节数组转换为字符串?

How to convert array byte to string in c ++?

byte S[5] = {0x48, 0x00, 0x65, 0x00, 0x6C}

我想知道如何将上面的字节数组转换成字符串

将上述字节数组转为字符串时,应输出"Hello"

试了各种方法都没有解决

  1. String^ a = System::Convert::ToString(S);
  2. std::string s(reinterpret_cast <const char*> (S), 5);

输出了一个完全不同的字符串。我该怎么办?

首先:该字节数组不包含"Hello"。它看起来像是在 UTF-16 中编码 5 个 Unicode 字符所需的 10 个字节的一半。

要在 .Net 中的字节和字符串之间进行转换,包括 C++/CLI,您需要使用 Encoding classes. Based on the data you've shown here, you'll want to use Encoding::Unicode. To convert from bytes to a string, call GetString.

byte S[5] = {0x48, 0x00, 0x65, 0x00, 0x6C};

因为您使用了 [] 语法,所以这是一个原始 C 数组,而不是 .Net 管理的数组对象。因此,您需要使用带有原始指针和长度的重载。

String^ str = Encoding::Unicode->GetString(S, 5);

如果您使用 .Net 数组对象,调用它会更容易一些,因为数组 class 知道它的长度。

array<Byte>^ S = gcnew array<Byte> { 0x48, 0x00, 0x65, 0x00, 0x6C };
String^ str = Encoding::Unicode->GetString(S);