C# .NET: Converting a string of bits to a byte array

08 Jul

I needed a way to convert a string of bits to a byte array: string -> byte[]

For example take the string 101100110010001111
I need my byte[] to contain: 10001111b (143d), 11001100b (204d), 10b (2d)

I saw a bunch of solutions to this problem in this post but they were either inadequate or too complex for all possible scenarios.

I decided to try to devise my own solution:

        private static byte[] getBitwiseByteArray(string input)
            List<byte> byteList = new List<byte>();
            for (int i = input.Length - 1; i >= 0; i-=8)
                string byteString = "";
                for (int j = 0; (i - j) >= 0 && j < 8; j++)
                    byteString = input[i - j] + byteString;
                if (byteString != "")
                    byteList.Add(Convert.ToByte(byteString, 2));
            return byteList.ToArray();

Let’s take an example (for easy visualization of the logic): 101100110010001111

I need to first extract 8 bits at a time from right to left. Therefore my i iterator counts down from the end of the string to the beginning in sets of 8.

After extracting, I should get 10001111, 11001100, 10

The j iterator ensures that I don’t take more than 8 bits at a time. It also ensures that when there are less than 8 bits left in the string (as in the case of 10 where only 2 bits were left), I stop extracting at that stage.

byteString contains at most 8 bits and is ready to be converted to a byte type using the Convert.ToByte function with the binary format specified.

1 Comment

Posted by on July 8, 2011 in .NET Framework Development, C#


Tags: , , , , , , , , , , ,

One response to “C# .NET: Converting a string of bits to a byte array

  1. BigYetti

    January 31, 2013 at 6:43 am

    Excellent. Works great. Just what I needed. Thank you!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: