最近公司要作一個操做日誌的模塊,若是將操做日誌以字符串的形式存到後臺數據庫,很是浪費內存,不可取,特地寫了字符串與二進制相互轉換的函數。數據庫
1 private string StringToBinary(string str) 2 { 3 byte[] data = Encoding.Unicode.GetBytes(str); 4 StringBuilder sb = new StringBuilder(data.Length*8); 5 foreach (byte item in data) 6 { 7 sb.Append(Convert.ToString(item,2).PadLeft(8,'0')); 8 } 9 return sb.ToString(); 10 }
1 private string BinaryToString(string str) 2 { 3 System.Text.RegularExpressions.CaptureCollection cs = System.Text.RegularExpressions.Regex.Match(str,@"([01]{8})+").Groups[1].Captures; 4 byte[] data = new byte[cs.Count]; 5 for (int i = 0; i < cs.Count; i++) 6 { 7 data[i] = Convert.ToByte(cs[i].Value,2); 8 } 9 return Encoding.Unicode.GetString(data,0,data.Length); 10 }
下面隨便寫了一條Sql語句,便於測試二者是否轉換成功?ide
轉碼成功!函數