Page 1 of 1
C# Non-ASCII-Printable Bytes To String
Posted: Wed Apr 15, 2009 6:15 pm
by Zone 117
(C#) I'm trying to convert bytes (from an image) that are not ASCII-printable into a string.
Meaning..
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(myBytes);
..does not work, it will show ???? characters.
Any help appreciated.
Re: C# Non-ASCII-Printable Bytes To String
Posted: Wed Apr 15, 2009 7:23 pm
by LuxuriousMeat
Zone 117 wrote:(C#) I'm trying to convert bytes (from an image) that are not ASCII-printable into a string.
Meaning..
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(myBytes);
..does not work, it will show ???? characters.
Any help appreciated.
Uh, are you trying to like show the hexadecimal value of the bytes?
If so use this:
Code: Select all
str = BitConverter.GetString(myBytes);
That will output the hexadecimal value of each byte a delimits each with a dash.
Re: C# Non-ASCII-Printable Bytes To String
Posted: Wed Apr 15, 2009 7:36 pm
by Zone 117
I started trying to use the BitConverter a little bit ago. As far as I can see, it converts the bytes to hex correctly. However when I convert the hex back into bytes, half the file is empty.
What method would you use to convert them back into bytes?
Thanks.
Re: C# Non-ASCII-Printable Bytes To String
Posted: Wed Apr 15, 2009 8:38 pm
by LuxuriousMeat
Zone 117 wrote:I started trying to use the BitConverter a little bit ago. As far as I can see, it converts the bytes to hex correctly. However when I convert the hex back into bytes, half the file is empty.
What method would you use to convert them back into bytes?
Thanks.
Here's one I use:
Code: Select all
byte[] TextStringToBytes(string str)
{
string[] parts = str.Split(new char[] { '-' });
if (parts.Length < 1) return new byte[0];
byte[] bytes = new byte[parts.Length];
for (int x = 0; x < parts.Length; x++)
if (!byte.TryParse(parts[x], out bytes[x])) return new byte[0];
return bytes;
}
Example of use:
Code: Select all
string str = "00-02-03-04";
byte[] b = TextStringToBytes(str);