Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Encoding.ASCII.GetString() returns "??" instead of actual string, why? [duplicate]

Tags:

c#

This is my piece of code (file is a HttpPostedFileBase type):

var imageStream = file.InputStream;
var header = new Byte[4];
imageStream.Read(header, 0, header.Length);

Now, while my code runs, i place a breakpoint, and in my immediate window i check values:

header
{byte[4]}
    [0]: 255
    [1]: 216
    [2]: 255
    [3]: 224

But, when i want to convert this byte array to string of ASCII, i get this (values obtained by immediate window):

Encoding.ASCII.GetString(header)
"????"
Encoding.ASCII.GetString(header, 0, 2)
"??"

What am I doing wrong?

like image 270
ojek Avatar asked Nov 23 '25 03:11

ojek


1 Answers

Characters above 127 cannot be represented as ASCII (which is a 7-bit encoding), and are therefore turned into ?.

What are you trying to achieve? There are many other encodings which may be more suitable for what you're trying to do - or no encoding at all maybe. It is important to understand that a char is not equivalent to a byte.

If the header is a "fixed" 4-byte sequence, don't use characters but rather the bytes directly (or an integer representation - see the BitConverter class for converting byte arrays to other things).

like image 157
Lucero Avatar answered Nov 24 '25 15:11

Lucero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!