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"); |
Binary to string method doesn’t work with cyrillic..
These methods do the job but aren’t efficient. And they assume the input you wish to convert to binary is an integer — this character parsing chokes on types whose string representation includes a decimal point (float, double, decimal). If you know the numerical type (int, uint, long, ulong, etc.) just use .NET’s built-in BCL Convert.ToString() method. For example:
For the sake of curiosity I wrote a quick test to compare StringToBinary() with Convert.ToString() for myLongNumber, each running for 1 million iterations, running on a Core 2 Duo w/ 3GB RAM. StringToBinary() takes an average of 3818 milliseconds while Convert.ToString() takes an average of 955 milliseconds.
You might be thinking that StringToBinary() is superior because it accepts numerical values of arbitrary size and there fore generates arbitrary-length binary string representations of those values, but the performance is a big penalty to pay. Additionally, BinaryToString() should validate that the parameter ‘data’ passed into the method doesn’t contain invalid characters (anything other than “0” and “1”). This validation would further slow performance.
More generally, because StringToBinary() accepts a string-formatted representation of a numerical value (that isn’t validated) you’re losing all the benefits of strong typing in C#. Unless you have a very good reason for needing this kind of “flexification” — and perhaps there are a few edge or corner cases — I recommend avoiding these approaches.
For the curious: my test harness code:
Very helpful. Nice work. Thanks.
Several thanks for the wonderful post
Terrific work! This is the type of info that should be shared around the net. Shame on the search engines for not positioning this post higher!
Hey there, You’ve done a great job. I will definitely digg it and personally suggest to my friends. I’m confident they
will be benefited from this site.