C#中 二进制与字符串
/// <summary>
/// 将 字符串 转成 二进制 “10011100000000011100011111111101”
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string Encode(string s)
{
byte[] data = Encoding.Unicode.GetBytes(s);
StringBuilder result = new StringBuilder(data.Length * 8);
foreach (byte b in data)
{
result.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
return result.ToString();
}
/// <summary>
/// 将二进制 “10011100000000011100011111111101” 转成 字符串
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string Decode(string s)
{
System.Text.RegularExpressions.CaptureCollection cs =
System.Text.RegularExpressions.Regex.Match(s, @"([01]{8})+").Groups[1].Captures;
byte[] data = new byte[cs.Count];
for (int i = 0; i < cs.Count; i++)
{
data[i] = Convert.ToByte(cs[i].Value, 2);
}
return Encoding.Unicode.GetString(data, 0, data.Length);
}