Convert string to binary and binary to string in C#

FrankYou發表於2015-12-08

String to binary method:

 1 public static string StringToBinary(string data)
 2 {
 3     StringBuilder sb = new StringBuilder();
 4  
 5     foreach (char c in data.ToCharArray())
 6     {
 7         sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
 8     }
 9     return sb.ToString();
10 }

Binary to string method:

 1 public static string BinaryToString(string data)
 2 {
 3     List<Byte> byteList = new List<Byte>();
 4  
 5     for (int i = 0; i < data.Length; i += 8)
 6     {
 7         byteList.Add(Convert.ToByte(data.Substring(i, 8), 2));
 8     }
 9     return Encoding.ASCII.GetString(byteList.ToArray());
10 }

 

相關文章