Reputation: 127
One way or another, all digital data is stored in 0 and 1. That's the principle of binary data, I guess.
Is there a method or package that can show you the binary code of a file/single-exe-program of how it is actually being stored in the 0/1 format??
I would see it like: - import a certain, random file - convert it to it's 0/1 format - store the the 1/0-data in a txt (streamwriter/binarywriter)
if yes, is this available in any .NET language (pref: c#)?
Upvotes: 0
Views: 241
Reputation: 20090
this will stream the conversion, useful if you have huge file.
using System;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var buffer = new byte[1024];
int pos = 0;
using (var fileIn = new FileStream(@"c:\test.txt", FileMode.Open, FileAccess.Read))
using (var fileOut = new FileStream(@"c:\test.txt.binary", FileMode.Create, FileAccess.Write))
while((pos = fileIn.Read(buffer,0,buffer.Length)) > 0)
foreach (var value in buffer.Take(pos).Select(x => Convert.ToString(x, 2).PadLeft(8, '0')))
fileOut.Write(value.Select(x => (byte)x).ToArray(), 0, 8);
}
}
}
Upvotes: 1
Reputation: 28654
I think this is something what you are looking for:
byte [] contents = File.ReadAllBytes(filePath);
StringBuilder builder = new StringBuilder();
for(int i = 0; i<contents .Length; i++)
{
builder.Append( Convert.ToString(contents[i], 2).PadLeft(8, '0') );
}
Now, you can for example write builder
contents to a text file.
Upvotes: 1
Reputation: 13059
A solution using FileStream
, StreamWriter
, StringBuilder
and Convert
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(InputFILEPATH, FileMode.Open))
{
while (fs.Position != fs.Length)
{
sb.Append(Convert.ToString(fs.ReadByte(),2));
}
}
using (StreamWriter stw = new StreamWriter(File.Open(OutputFILEPATH,FileMode.OpenOrCreate)))
{
stw.WriteLine(sb.ToString());
}
Console.ReadKey();
}
Upvotes: 0
Reputation: 218798
Essentially you just need to break this into two steps:
var fileBytes = File.ReadAllBytes(someFileName);
The second step is less straightforward, but still pretty easy:
var byteString = string.Concat(fileBytes.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')))
The idea here is that you select each byte individually, converting each one to a binary string (pad left so each one is 8 characters, since many bytes have leading zeroes), and concatenate all of those into a single string. (Courtesy in part of @xanatos' comment below.)
Upvotes: 2
Reputation: 13676
You can open the file in binary mode. Didn't test it but it should work :
BitArray GetBits(string fuleSrc)
{
byte[] bytesFile;
using (FileStream file = new FileStream(fuleSrc, FileMode.Open, FileAccess.Read))
{
bytesFile = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
}
return new BitArray(bytesFile);
}
Upvotes: 0