views:

410

answers:

4

I want to convert a binary file into an array of ascii charcters . how can I do that . thank you .

A: 

You can read each character and just cast it to a char. That would convert every byte to an ascii character. Is that what you are looking to do?

Stephan
+2  A: 

Check out BASE64 or UUEncoding. I assume you're wanting to use only printable characters from the 256-char ASCII set.

BASE64 uses only 64 characters (sometimes this is used when sending binary via email for example). This causes the output to grow in size -- something you have to consider in your situation.

Drew Noakes
Yes, and it is simple to do this in C# with Convert.ToBase64String()
PeterAllenWebb
+1  A: 
StreamReader reader = new StreamReader("pathtoyourbinaryfile", System.Text.Encoding.ASCII);
char[] text = reader.ReadToEnd().ToCharArray();
plinth
+4  A: 

It depends on what you want to do with it. Ascii is supposed to be 7bits (0-127 are well defined, the other characters are codepage dependant). So plain ASCII encoding can lead to nasty surprises (among which are non printables characters as nulls...)

If you want to have something printable out of your byte array, you should not convert them with an ASCII encoding. You'd better encode it in Base64, which is a safe (albeit not too optimal size-wise) way to encode binary in strings.

To encode your bytes in Base64, you can just go with:

string result = System.Convert.ToBase64String(yourByteArray);
Yann Schwartz
True, although converting the Base64 string to ASCII will be safe, and result only in printable characters.
PeterAllenWebb