50

I want to make a method that takes any file and reads it as an array of 0s and 1s, i.e. its binary code. I want to save that binary code as a text file. Can you help me? Thanks.

Boris
  • 9,986
  • 34
  • 110
  • 147
  • 1
    Your question is unclear. What exactly should the two files look like? – SLaks Mar 11 '10 at 15:29
  • 1
    I think he wants to store the bit pattern of a file into a text file. – Oded Mar 11 '10 at 15:32
  • 1
    Is the source file binary or encoded (textual, either as ASCII, UTF-8, UTF-16, etc)? In other words, if you open the file in a text editor like Notepad, do you see zeros and ones? – Pat Mar 11 '10 at 15:55

5 Answers5

71

Quick and dirty version:

byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();

foreach(byte b in fileBytes)
{
    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  
}

File.WriteAllText(outputFilename, sb.ToString());
Chris Doggett
  • 19,959
  • 4
  • 61
  • 86
  • 3
    @Andrey: See "quick and dirty". Obviously, in production, something using file streams would be much better. The important part is converting from bytes to binary strings. – Chris Doggett Mar 11 '10 at 17:42
23

Well, reading it isn't hard, just use FileStream to read a byte[]. Converting it to text isn't really generally possible or meaningful unless you convert the 1's and 0's to hex. That's easy to do with the BitConverter.ToString(byte[]) overload. You'd generally want to dump 16 or 32 bytes in each line. You could use Encoding.ASCII.GetString() to try to convert the bytes to characters. A sample program that does this:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    Thank you for your answer. Hmmm.. something doesn't seem to work, as I'm not getting the 0s and 1s. Instead, I am getting the same effect as if I would chose to open a file in notepad. – Boris Mar 11 '10 at 16:18
  • 1
    Yes you do, they are encoded in hex. Not the same thing you'd see in notepad. Backgrounder: http://en.wikipedia.org/wiki/Hexadecimal – Hans Passant Mar 11 '10 at 16:28
  • 1
    This method reads the file, can you provide a method that writes the binary to the file or writes the binary data to the file then converts to hex to read back the way you have it here? – shawn Dec 11 '14 at 16:53
7

You can use BinaryReader to read each of the bytes, then use BitConverter.ToString(byte[]) to find out how each is represented in binary.

You can then use this representation and write it to a file.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
7
using (FileStream fs = File.OpenRead(binarySourceFile.Path))
    using (BinaryReader reader = new BinaryReader(fs))
    {              
        // Read in all pairs.
        while (reader.BaseStream.Position != reader.BaseStream.Length)
        {
            Item item = new Item();
            item.UniqueId = reader.ReadString();
            item.StringUnique = reader.ReadString();
            result.Add(item);
        }
    }
    return result;  
Daniel Puiu
  • 962
  • 6
  • 21
  • 29
guest
  • 115
  • 1
  • 2
5

Use simple FileStream.Read then print it with Convert.ToString(b, 2)

Andrey
  • 59,039
  • 12
  • 119
  • 163