C#二进制与字符串之间的相互转换

 1     /// <summary>
 2     /// 将字符串转成二进制
 3     /// </summary>
 4     /// <param name="s"></param>
 5     /// <returns></returns>
 6     public static string bianma(string s)
 7     {
 8         byte[] data = Encoding.Unicode.GetBytes(s);
 9         StringBuilder result = new StringBuilder(data.Length * 8);
10 
11         foreach (byte b in data)
12         {
13             result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
14         }
15         return result.ToString();
16     }
复制代码

将二进制转成 字符串

复制代码
 1     /// <summary>
 2     /// 将二进制转成字符串
 3     /// </summary>
 4     /// <param name="s"></param>
 5     /// <returns></returns>
 6     public static string jiema(string s)
 7     {
 8         System.Text.RegularExpressions.CaptureCollection cs =
 9             System.Text.RegularExpressions.Regex.Match(s, @"([01]{8})+").Groups[1].Captures;
10         byte[] data = new byte[cs.Count];
11         for (int i = 0; i < cs.Count; i++)
12         {
13             data[i] = Convert.ToByte(cs[i].Value, 2);
14         }
15         return Encoding.Unicode.GetString(data, 0, data.Length);
16     }
posted @ 2013-12-23 12:56  盛开的雨季  阅读(38456)  评论(0编辑  收藏  举报