在网络传输和文件操作中,如果数据量很大,需要将其划分为较小的快,此时可能出现一个数据块的末尾是一个不匹配的高代理项,而与其匹配的低代理项在下一个数据块。

这时候使用Encoding的GetBytes方法处理较为麻烦,我们直接使用Encoder处理。

Encoder可以将一组字符编码为一个字节序列。而Decoder可以将已编码的字节序列解码为字符序列。

 

Encoding 实现。

Encoding.GetBytes。

Encoder 还保留尾随字符数据块的末尾,并在下一步编码操作中使用尾随字符。

GetEncoder 在网络传输和文件操作很有用,因为这些操作通常处理的数据而不是完整的数据流块。

 

Encoding 实现。

GetEncoder 非常有用的网络传输和文件操作,因为这些操作通常处理的数据而不是完整的数据流块。

 

 1         string str = "在下坂本,有何贵干@@";
 2         Char[] chars = str.ToCharArray();
 3         Debug.Log("String="+new string(chars));
 4         //获得Encoder实例;
 5         Encoder encoder  = Encoding.UTF8.GetEncoder();
 6         //计算字符序列化需要的字节数组长度;
 7         byte[] bytes = new byte[encoder.GetByteCount(chars,0,chars.Length,true)];
 8         //通过GetBytes转为字节序列;
 9         encoder.GetBytes(chars, 0, chars.Length, bytes, 0, true);
10         Debug.Log(BitConverter.ToString(bytes));
11         Debug.Log("Encoding.UTF8.GetString=" + Encoding.UTF8.GetString(bytes));
12         //获得Decoder实例;
13         Decoder decoder = Encoding.UTF8.GetDecoder();
14         //计算字节数组对应的字符数组长度;
15         int charSize = decoder.GetCharCount(bytes, 0, bytes.Length);
16         Char[] chs = new char[charSize];
17         //进行字符转换;
18         int charLength = decoder.GetChars(bytes, 0, bytes.Length, chs, 0);
19         Debug.Log("Decoder Bytes to String =" + new string(chs));

 

 

//output:

C# 字符编码解码 Encoder 和Decoder

 

 

MSDN Encoder >>>  https://msdn.microsoft.com/zh-cn/library/system.text.encoder%28v=vs.110%29.aspx

MSDN Decoder >>> https://msdn.microsoft.com/zh-cn/library/system.text.decoder%28v=vs.110%29.aspx

相关文章:

  • 2021-11-18
  • 2022-12-23
  • 2021-07-21
  • 2021-07-18
  • 2021-05-05
  • 2021-05-03
  • 2021-09-27
  • 2021-11-22
猜你喜欢
  • 2021-10-20
  • 2022-12-23
  • 2021-06-08
  • 2021-09-07
  • 2021-09-09
相关资源
相似解决方案