Converting a binary string representation into binary array in C#

Stum­bled across this ques­tion on Stack­Over­flow the oth­er day, def­i­nite­ly one for the inter­view! The ques­tion goes:

How do you con­vert a string such as “01110100011001010111001101110100” to a byte array then used File.WriteAllBytes such that the exact bina­ry string is the bina­ry of the file. In this case it would be the the text “test”.

Here’s my take on the answer :-)

var binaryStr = "01110100011001010111001101110100";

var byteArray = Enumerable.Range(0, int.MaxValue/8)
                          .Select(i => i*8)    // get the starting index of which char segment
                          .TakeWhile(i => i < binaryStr.Length)
                          .Select(i => binaryStr.Substring(i, 8)) // get the binary string segments
                          .Select(s => Convert.ToByte(s, 2)) // convert to byte
                          .ToArray();
File.WriteAllBytes("C:\temp\test.txt", byteArray);