1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class StrBinConvertor { /// <summary> /// 将 字符串 转成 二进制 “10011100000000011100011111111101” /// </summary> /// <param name="s"></param> /// <returns></returns> public static string StrToBin(string s) { var data = Encoding.Unicode.GetBytes(s); var result = new StringBuilder(data.Length * 8); foreach (var 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 BinToStr(string s) { var cs = System.Text.RegularExpressions.Regex.Match(s, @"([01]{8})+").Groups[1].Captures; var data = new byte[cs.Count]; for (var i = 0; i < cs.Count; i++) { data[i] = Convert.ToByte(cs[i].Value, 2); } return Encoding.Unicode.GetString(data, 0, data.Length); } } |