Search code examples
c++-cli

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


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

I want to know how to convert the above byte array to a string.

When converting the above byte array to a string, "Hello" should be output.

I tried various ways but it didn't solve at all.

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

A completely different string is output. What should I do?


Solution

  • First: That byte array doesn't contain "Hello". It looks like half of the 10 bytes needed to encode 5 Unicode characters in UTF-16.

    For converting between bytes and strings in .Net, including C++/CLI, you want to use the 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};
    

    Because you used the [] syntax, this is a raw C array, not a .Net managed array object. Therefore, you'll need to use the overload that takes a raw pointer and a length.

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

    If you use a .Net array object, calling it will be a bit easier, as the array class knows its length.

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