简体   繁体   中英

How can I prevent a change in value of upper 8-bit ASCII when storing a byte array to a string?

I am working directly with a device that I need to be able to send 8-bit ASCII. I am trying save a byte array that may have values greater than 127 to a string. These values are being converted to 0xfffd instead of the zero prefixed character I expect.

For example I would expect that with the example below the third char in the string would be 0x00AA but in reality it is 0xffdd .

If I do a direct assignment it works.

test = "ABC" + (char)0xAA + "DEF";

I've tried alternate encodings such as "windows-1250" with differing results ( 0x201a ), but not what I want. Picking an ASCII encoding fails ( 0x003f ) as well.

How can I get the correct conversion?

Sample code:

  byte[] byteArray = new byte[30];

  byteArray[0] = 0x41; // A
  byteArray[1] = 0x42; // B
  byteArray[2] = 0x43; // C
  byteArray[3] = 0xAA; // Special character in upper 128 character set
  byteArray[4] = 0x44; // D
  byteArray[5] = 0x45; // E
  byteArray[6] = 0x46; // F

  string test = System.Text.Encoding.UTF8.GetString(byteArray).TrimEnd('\0');
  if (!test.Equals("ABC" + (char)0xAA + "DEF")) {
    // It fails
    // test[3] == 0xfffd not 0x00aa
  } 

I think my problem is that no matter what "encoding" I use it will try and remap characters to match the target. Manually casting each byte as a char solves my issue.

Usage: string test = ByteArrayToString(byteArray);

/// <summary>
/// Convert a zero terminated byte array to a string.
/// </summary>
/// <param name="byteArray"></param>
/// <returns></returns>
private static string ZeroTerminatedByteArrayToString(byte[] byteArray)
{
  // This routine is used to map a byte array unmodified to a string
  // Each character is stored with as a double byte with leading zero.
  // Using the encodings to convert will try and remap some characters
  // System.Text.Encoding.GetEncoding("437").GetString(byteArray);
  // System.Text.Encoding.UTF8.GetString(byteArray);

  string result = "";
  for (int i = 0; i < byteArray.Length; i++) {
    if (byteArray[i] == 0) { break; }
    result = result + (char)byteArray[i];
  }
  return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM