Binary to string

I am trying to read a binary (e.g. an executable) in a line and then write it

FileStream fs = new FileStream("C:\\tvin.exe", FileMode.Open); BinaryReader br = new BinaryReader(fs); byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length)); System.Text.Encoding enc = System.Text.Encoding.ASCII; string myString = enc.GetString(bin); fs.Close(); br.Close(); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] rebin = encoding.GetBytes(myString); FileStream fs2 = new FileStream("C:\\tvout.exe", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs2); bw.Write(rebin); fs2.Close(); bw.Close(); 

this does not work (the result is exactly the same size in bytes, but cannot work)

if I do bw.Write (bin), the result is fine, but I have to save it in a line

+6
string c # binaryfiles
source share
2 answers

When you decode bytes into a string and encode them back to bytes, you lose information. ASCII in particular is a very bad choice for this, since ASCII will give out a lot of information along the way, but you run the risk of losing information when encoding and decoding regardless of the type of encoding you choose, so you are not on the right path.

What you need is one of the BaseXX routines that encodes binary data for printable characters, usually for storage or transmission over a medium that allows only text (email and usenet come to mind.)

Ascii85 is one such algorithm, and the page contains links to various implementations. It has a 4: 5 ratio, which means that 4 bytes will be encoded as 5 characters (an increase of 25%).

Otherwise, Base64 already has an encoding routine built into .NET. It has a ratio of 3: 4 (an increase of 33%), here:

Here, your code may look using these methods:

 string myString; using (FileStream fs = new FileStream("C:\\tvin.exe", FileMode.Open)) using (BinaryReader br = new BinaryReader(fs)) { byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length)); myString = Convert.ToBase64String(bin); } byte[] rebin = Convert.FromBase64String(myString); using (FileStream fs2 = new FileStream("C:\\tvout.exe", FileMode.Create)) using (BinaryWriter bw = new BinaryWriter(fs2)) bw.Write(rebin); 
+15
source share

I do not think that you can represent all bytes with ASCII in this way. Base64 is an alternative, but with a 3: 4 ratio between bytes and text.

+2
source share

All Articles