Search code examples
c#stringbinarydata-conversion

Convert binary data in a text file to text format


I want to read a .txt file containing "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100" and want to convert this binary data to corresponding text format "HelloWorld" in c# Please help

Binary To Corresponding ASCII String Conversion

This is not giving me answers.


Solution

  • Here you go

    1. split it into 8 character length chunks (one byte each chunk)
    2. convert each chunk with Convert.ToByte(string input, int base) into type byte
    3. convert the bytes into text with System.Text.Encoding.UTF8.GetString(byte[] input)

    https://dotnetfiddle.net/w37fvg

    string input = "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100";
    List<byte> bList = new List<byte>();
    for (int i = 0; i < input.Length; i += 8)
    {
        bList.Add(Convert.ToByte(input.Substring(i, 8), 2));
    }
    string result = Encoding.UTF8.GetString(bList.ToArray());
    Console.WriteLine(result);