1

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.

  • *This is not giving me answers.* - the accepted answer of the duplicate target (which is almost identical to the answer below) converts the string that you gave as an example to "Hello World". If this is not what you want, you need to explain what else you're looking for. – jps Jun 07 '21 at 15:18

1 Answers1

0

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);
fubo
  • 44,811
  • 17
  • 103
  • 137
  • the above program gives Exception: System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string. – Keerthi Vasan Jun 07 '21 at 15:40
  • already handled in [System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string. in c#](https://stackoverflow.com/q/67875389) – jps Jun 07 '21 at 17:02
  • @KeerthiVasan the code above gives no exception - just look at the fiddle. But you have to make sure that `input.length%8==0` – fubo Jun 08 '21 at 05:39