0

What is wrong with this code? Why the differences?

byte [] data = new byte [] {0x21, 0x4B, 0x9B, 0xE1, 0x2D, 0xA7, 0x4B, 0x93, 0x1E, 0x3F, 0xDA, 0x4F, 0xB1};
Console.WriteLine(BitConverter.ToString(data));

string dataStr = ASCIIEncoding.ASCII.GetString(data);       
byte[] ca = ASCIIEncoding.ASCII.GetBytes(dataStr);
Console.WriteLine(BitConverter.ToString(ca));

Output:

21-4B-9B-E1-2D-A7-4B-93-1E-3F-DA-4F-B1

21-4B-3F-3F-2D-3F-4B-3F-1E-3F-3F-4F-3F

Community
  • 1
  • 1
se7en
  • 3
  • 1

1 Answers1

2

ASCII doesn't define character codes above 7F, and it seems that ASCIIEncoding.ASCII.GetString() chooses to replace invalid bytes with 3F, which represents the character ?.

You might want to read Joel Spolsky's excellent article on encoding.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81