【问题标题】:Array and String Encoding数组和字符串编码
【发布时间】:2013-01-14 15:41:55
【问题描述】:

当我这样做时

string s = Encoding.Unicode.GetString(a);
byte[] aa = Encoding.Unicode.GetBytes(s);

我有不同的数组 (a != aa) 。 为什么

但是当我这样做的时候呢?没关系

string s = Encoding.Default.GetString(a);
byte[] aa = Encoding.Default.GetBytes(s);

【问题讨论】:

  • 什么编码是in?他们怎么不相等?您是否在检查每个元素的位置?
  • 能否添加a的值,以便您的问题可以直接复制?
  • 不要混淆编码和加密
  • @Zhenia 但是数组包含什么?

标签: c# encoding


【解决方案1】:

那是因为您使用的是反向编码。编码用于将字符串编码为字节,然后再次编码回字符串。

在编码中,每个字符都有相应的字节集,但并非每个字节集都必须有相应的字符。这就是为什么你不能把任意字节解码成字符串。

使用编码Default 会以这种方式误用它,因为它只为每个字符使用一个字节,而每个字节码恰好都有一个字符。不过,这样使用它仍然没有意义。

【讨论】:

  • 哇 :) 你闻到知识+1
【解决方案2】:

为了补充 Guffa 的答案,这里有一个详细示例,说明您的代码如何针对某些字节序列失败,例如 0, 216

// Let's start with some character from the ancient Aegean numbers:
// The code point of Aegean One is U+10107. Code points > U+FFFF need two
// code units with two bytes each if you encode them in UTF-16 (Encoding.Unicode)
string aegeanOne = char.ConvertFromUtf32(0x10107);
byte[] aegeanOneBytes = Encoding.Unicode.GetBytes(aegeanOne);
// Length == 4 (2 bytes each for high and low surrogate)
// == 0, 216, 7, 221

// Let's just take the first two bytes.
// This creates a malformed byte sequence,
// because the corresponding low surrogate is missing.
byte[] a = new byte[2];
a[0] = aegeanOneBytes[0]; // == 0
a[1] = aegeanOneBytes[1]; // == 216

string s = Encoding.Unicode.GetString(a);
// == replacement character � (U+FFFD),
// because the bytes could not be decoded properly (missing low surrogate)

byte[] aa = Encoding.Unicode.GetBytes(s);
// == 253, 255 == 0xFFFD != 0, 216

string s2 = Encoding.Default.GetString(a);
// == "\0Ø" (NUL + LATIN CAPITAL LETTER O WITH STROKE)
// Results may differ, depending on the default encoding of the operating system

byte[] aa2 = Encoding.Default.GetBytes(s2);
// == 0, 216

【讨论】:

    【解决方案3】:

    这意味着您的 byte[] a 的字节顺序不符合 Unicode 规则。

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2013-05-11
      • 2016-01-02
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多