7

I am receiving a unicode message via the network, which looks like:

74 00 65 00 73 00 74 00 3F 00

I am using a BinaryReader to read the stream from my socket, but the problem is that it doesn't offer a "ReadWideString" function, or something similar to it. Anyone an idea how to deal with this?

Thanks!

3 Answers 3

16

Simple!

string str = System.Text.Encoding.Unicode.GetString(array);

where array is your array of bytes.

Sign up to request clarification or add additional context in comments.

Comments

8

Strings in C# are Unicode by default. Try

string converted = Encoding.Unicode.GetString(data);

where data is a byte[] array containing your Unicode data. If your data is big endian, you can try

string converted = Encoding.BigEndianUnicode.GetString(data);

1 Comment

Each byte every 2 is equal to 0, it's rather unlikely that it's utf-8.
6

You could use a StreamReader like this:

StreamReader sr = new StreamReader(stream, Encoding.Unicode);

If your stream only contains lines of text then StreamReader is more suitable than BinaryReader. If your string is embedded inside binary data then it is probably better to decode the string using the Encoding.GetString method as others have suggested

Comments

Your Answer

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