You can start by breaking a string into a sequence of 8-character strings, then converting these strings to bytes, and finally writing the bytes to a file
string input = "01110100011001010111001101110100"; var bytesAsStrings = input.Select((c, i) => new { Char = c, Index = i }) .GroupBy(x => x.Index / 8) .Select(g => new string(g.Select(x => x.Char).ToArray())); byte[] bytes = bytesAsStrings.Select(s => Convert.ToByte(s, 2)).ToArray(); File.WriteAllBytes(fileName, bytes);
EDIT: here's another way to split a string into 8-character chunks, maybe a little easier:
int nBytes = (int)Math.Ceiling(input.Length / 8m); var bytesAsStrings = Enumerable.Range(0, nBytes) .Select(i => input.Substring(8 * i, Math.Min(8, input.Length - 8 * i)));
If you know that the string length is a multiple of 8, you can make it even simpler:
int nBytes = input.Length / 8; var bytesAsStrings = Enumerable.Range(0, nBytes) .Select(i => input.Substring(8 * i, 8));
Thomas Levesque Aug 08 2018-10-10T00: 00Z
source share