0
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?

David Yaw
  • 27,383
  • 4
  • 60
  • 93
sese2323
  • 13
  • 3
  • 2
    `String^ a = System::Convert::ToString(S);` doesn't look like C++. – eerorika Sep 11 '19 at 20:36
  • 2
    Why should `hello` be printined? You have two `0x00` in the array which ar null terminators. – NathanOliver Sep 11 '19 at 20:38
  • What encoding are you using? ASCII is 7-bits. – Thomas Matthews Sep 11 '19 at 20:40
  • Added the "c++-cli" tag because `String^` is not valid syntax for pure C++, but is valid for Microsoft abominations. – Thomas Matthews Sep 11 '19 at 20:41
  • Is there anything stopping you from using a brute-force approach? For example, iterate through the array, if the byte is not a nul, append it to the string. – Thomas Matthews Sep 11 '19 at 21:21
  • `0x48, 0x00,` looks a lot like 16 bit wide character rather than the regular 8 bit representation you may be used to. See if `std::wstring` can help you out. If not, it's time [to delve into locales](https://en.cppreference.com/w/cpp/locale) – user4581301 Sep 11 '19 at 21:43
  • Possible duplicate of [Convert C++ byte array to a C string](https://stackoverflow.com/questions/57399227/convert-c-byte-array-to-a-c-string) – Ben Amos Sep 11 '19 at 21:51
  • Like this: std::string{ &s[0], &s[std::size(s)] } You might lose last character, strings are null terminated. – David Ledger Sep 11 '19 at 23:53
  • When converting to std::string your string will be cut off by the 0x00 character. This is counted as a null terminator. – David Ledger Sep 12 '19 at 00:00

1 Answers1

1

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);
David Yaw
  • 27,383
  • 4
  • 60
  • 93