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?

9
  • 2
    String^ a = System::Convert::ToString(S); doesn't look like C++. Commented Sep 11, 2019 at 20:36
  • 2
    Why should hello be printined? You have two 0x00 in the array which ar null terminators. Commented Sep 11, 2019 at 20:38
  • What encoding are you using? ASCII is 7-bits. Commented Sep 11, 2019 at 20:40
  • Added the "c++-cli" tag because String^ is not valid syntax for pure C++, but is valid for Microsoft abominations. Commented Sep 11, 2019 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. Commented Sep 11, 2019 at 21:21

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.