anurag
anurag

Reputation: 137

File.WriteAllBytes does not changes file to binary 10101011

I have a some confusion about the function File.WriteAllBytes.

Actually i read from an image file using

byte[] b =  System.IO.File.ReadAllBytes(textBox1.Text);

and then i wrote back the read data to a text file to see how it looks.

System.IO.File.WriteAllBytes(@"D:\abc.txt", b);

But the contents of abc.txt are not pure binary(1010110) , but they appear as :-

ëžÕwN±k›“ùIRA=Ï¥Dh﬒ȪÊj:³0Æî(À÷«3ÚÉid¤n•O<‰-ª@–¢)cùY³Ö˜K„TûËEÇóþ}wtÑ+²=£v*NÌ!\ äji;âíÇ8ÿ ?犴ö¬€Áç#µ:+ŠVÜ„©³Û?çù~VèÖ·ÂËSŠE7RH8}GJGfT?Ý?çüÿ œÌÊR"6­ÓŠY¬Š¬L§|n¹> ÷’ÃU{D®t­vE!3** Ý× õ¨ã(¨qžO§ùÿ >Ó¥¤…K€@N{ñM(ÊÅ€ûÃŒRtj/²Æ¤¶¹RÁŽxqþÏó@KŒîn皘æ0C/-Ž1Mu>oÊ }é5(­Q¢i±pIôÀôÿ ?çÒÂB-á.ãï©Ú}êB®æÇÌyÿ ?çüU¥mã$”ã ‚DiFQ¸'µ,ARGLäc¯4%ËŸÃœsŸóù~H 3d‚zŠ‡Ø........................................

Are the binary 1s and 0s getting converted to some other number system comprising of so many symbols ??

Upvotes: 0

Views: 1149

Answers (2)

Daniel
Daniel

Reputation: 411

A text-viewer like NotePad will try to interpret the bytes as text, probably it will interpret the bytes as Unicode.

If you want to see the actual 0's and 1's then read in the image as bytes and convert the byte array to a string of 0's and 1's, for this you could use:

public static string ByteArrayToString(byte[] ba)
{
   string hex = BitConverter.ToString(ba);
   return hex.Replace("-","");
}

The conversion function is copied from here (accepted answer). Remember, this string will not anymore be interpretable as image, essentially this will simply be a large string of 0's and 1's.

Upvotes: 1

Sam Harwell
Sam Harwell

Reputation: 99859

Each byte in the file is comprised of 8 bits. When you use ReadAllBytes, you get an array of byte instances, where each byte represents a number between 0 and 255 (inclusive). One representation of the number 86 that is readable by humans is 01010110. However, when you use WriteAllBytes, it writes the sequence of bytes in the original form. Notepad is then loading the file and displaying each byte as a single character (or in some encodings treating multiple bytes as a single character to display). However, if you were to write "01010110" to a file such that Notepad shows those numbers, you would actually end up writing 8 bytes, not 8 bits, like this, where each set of 8 bits represents the digit '0' or '1':

00110000 00110001 00110000 00110001 00110000 00110001 00110001 00110000

Upvotes: 1

Related Questions