C#读取unicode?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1197445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# read unicode?
提问by
I am receiving a unicode message via the network, which looks like:
我通过网络收到一条 unicode 消息,它看起来像:
74 00 65 00 73 00 74 00 3F 00
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?
我正在使用 BinaryReader 从我的套接字读取流,但问题是它不提供“ReadWideString”函数或类似的函数。任何人都知道如何处理这个问题?
Thanks!
谢谢!
采纳答案by Dmitry Brant
Simple!
简单的!
string str = System.Text.Encoding.Unicode.GetString(array);
where arrayis your array of bytes.
array你的字节数组在哪里。
回答by Charlie Salts
Strings in C# are Unicode by default. Try
C# 中的字符串默认为 Unicode。尝试
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
其中 data 是包含您的 Unicode 数据的 byte[] 数组。如果你的数据是大端的,你可以试试
string converted = Encoding.BigEndianUnicode.GetString(data);
回答by Martin Liversage
You could use a StreamReaderlike this:
你可以使用StreamReader这样的:
StreamReader sr = new StreamReader(stream, Encoding.Unicode);
If your stream only contains lines of text then StreamReaderis more suitable than BinaryReader. If your string is embedded inside binary data then it is probably better to decode the string using the Encoding.GetStringmethod as others have suggested
如果您的流仅包含文本行,则StreamReader比BinaryReader. 如果您的字符串嵌入在二进制数据中,那么使用Encoding.GetString其他人建议的方法对字符串进行解码可能会更好

