6 Responses to Convert string to binary and binary to string in C#

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:

1

2

longmyLongNumber=long.MaxValue/175;

stringmyLongNumberInBinary=Convert.ToString(myLongNumber,2);

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.