Convert Binary Files to Text


Hello, I'm looking for help with a little problem I have

My question is how can I convert the text that contains a file.txt to binary and vice versa

I understand that using the BinaryWriter class I can convert text to binary in case with what I have more problem and it confuses me is when I want to return the binary numbers to text that contains a file.txt

for example in the file.txt entry "hello world" when I convert it to binary it would be [][]|

So my question is how do I get these binary numbers back to text?

any advice?

asked by Jeff 01.10.2017 в 10:05

1 answer


Good Jeff,

You can choose to use the BinaryWriter , or you can use these methods that do not use any external libraries like the following:

Function to pass text to binary:

public static string StringToBinary(string texto)
    StringBuilder sb = new StringBuilder();

    foreach (char c in texto.ToCharArray())
        sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
    return sb.ToString();

Function to pass binaries to text:

public static string BinaryToString(string texto)
    List<Byte> byteList = new List<Byte>();

    for (int i = 0; i < texto.Length; i += 8)
        byteList.Add(Convert.ToByte(texto.Substring(i, 8), 2));
    return Encoding.ASCII.GetString(byteList.ToArray());
answered by 02.10.2017 в 12:52