C# byte array 跟 string 互转

用 System.Text.Encoding.Default.GetString() 转换时,byte array 中大于 127 的数据转 string 时会出问题。

把这里的 Default 换成 ASCII,UTF8,Unicode 都会有问题(转成的 string 再转回 byte array 数据不一致)。

转过去还能再转回来的才是真汉子。这时需要用 System.Buffer.BlockCopy 

 1 using System.IO;
 2 using System;
 3 
 4 class Program
 5 {
 6     static void Main()
 7     {
 8         byte[] buffer = new byte[] {1, 2, 196, 3};
 9         
10         char[] chars = new char[buffer.Length / sizeof(char)];
11         System.Buffer.BlockCopy(buffer, 0, chars, 0, buffer.Length);
12         string str = new string(chars);
13         
14         byte[] fuck = new byte[str.Length * sizeof(char)];
15         System.Buffer.BlockCopy(str.ToCharArray(), 0, fuck, 0, fuck.Length);
16 
17         for (int i=0; i < fuck.Length; ++i)
18         {
19             Console.Write("{0} ", fuck[i]);
20         }
21         Console.WriteLine("");
22     }
23 }

这个问题让我查了好久好久。又忍不住感叹,妈的就不能做成像 C 语言那样单纯简洁吗

原文地址:https://www.cnblogs.com/hangj/p/6435902.html