Tag Archives: string to binary
Convert string to binary and binary to string in C#
The following two snippets allow you to convert a string to binary text and also to convert binary back to string.
String to binary method:
1 2 3 4 5 6 7 8 9 10 | public static string StringToBinary(string data) { StringBuilder sb = new StringBuilder(); foreach (char c in data.ToCharArray()) { sb.Append(Convert.ToString(c, 2).PadLeft(8, '0')); } return sb.ToString(); } |
Binary to string method:
1 2 3 4 5 6 7 8 9 10 | public static string BinaryToString(string data) { List<Byte> byteList = new List<Byte>(); for (int i = 0; i < data.Length; i += 8) { byteList.Add(Convert.ToByte(data.Substring(i, 8), 2)); } return Encoding.ASCII.GetString(byteList.ToArray()); } |
Usage:
1 2 3 4 5 | // returns "01100110011011000111010101111000011000100111100101110100011001010111001100101110011000110110111101101101" StringToBinary("fluxbytes.com") // returns "fluxbytes.com" BinaryToString("01100110011011000111010101111000011000100111100101110100011001010111001100101110011000110110111101101101"); |
Posted in C#.
Tagged binary, binary to string, C#, csharp, snippet, string to binary, winforms