Reading special characters from Byte []

I am writing and reading from Mifare cards - RFID .

In WRITE to the map, I use Byte[] as follows:

 byte[] buffer = Encoding.ASCII.GetBytes(txt_IDCard.Text); 

Then, before READ from the map, I get some error with special characters when it should show me é, ã, õ, á, à... Instead, do I get ? :

 string result = System.Text.Encoding.UTF8.GetString(buffer); string result2 = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length); string result3 = Encoding.UTF7.GetString(buffer); 

For example: instead I get Àgua, amanhã, você I get / read ?gua, amanh?, voc? .
How can I solve it?

+7
source share
3 answers

ASCII, by its very definition, only supports 128 characters.

What you need is ANSI characters if you are reading legacy text.

You can use Encoding.Default instead of Encoding.ASCII to interpret characters on the current ANSI default code page.

Ideally, you know exactly which codepage you expect to use ANSI characters, and explicitly specify the codepage with this Encoding.GetEncoding(int codePage) overload , for example

 string result = System.Text.Encoding.GetEncoding(1252).GetString(buffer); 

Here is a very good Unicode man page: http://www.joelonsoftware.com/articles/Unicode.html

And here: http://msdn.microsoft.com/en-us/library/b05tb6tz%28v=vs.90%29.aspx

But maybe you can just use UTF8 when reading and writing

I do not know the details of the card reader. Are the data you read and write to the card just loading bytes?

If so, you can just use UTF8 to read and write, and everything will work. You need to use ANSI only if you are working with an obsolete device that expects (or provides) ANSI text. If the device simply stores bytes blindly, without implying any particular format, you can do what you like - in this case, just use UTF8.

+8
source

It seems that you are using characters that are not displayed in 7-bit ASCII, but in the "extensions" of ISO-8859-1 or ISO-8859-15. You will need to select a specific encoding to map to your byte array, and everything should work fine,

 byte[] buffer = Encoding.GetEncoding("ISO-8859-1").GetBytes(txt_IDCard.Text); 
+4
source

You have two problems:

  • ASCII only supports a limited number of characters.
  • You are currently using two different encodings for reading and writing.

You must write with the same coding as you.

Record

  byte[] buffer = Encoding.UTF8.GetBytes(txt_IDCard.Text); 

Reading

  string result = Encoding.UTF8.GetString(buffer); 
+1
source

All Articles