如何适当地从字符串中获取字节?

Joh*_*ohn 5 c# encoding

我有一个字符串变量,从中我可以通过以下循环获得以下字节:

Bytes I get: 1e 05 55 3c *e2 *91 6f 03 *fe 1a 1d *f4 51 6a 5e 3a *ce *d1 04 *8c 

With that loop:

  byte[] temp = new byte[source.Length];
  string x = "";
  for (int i = 0;i != source.Length;i++)
  {
    temp[i] = ((byte) source[i]);
  }
Run Code Online (Sandbox Code Playgroud)

现在我想简化该操作并使用 Encoding 的 GetBytes。问题是我无法适应适当的编码。例如,我得到的几个字节不正确:

Encoding.ASCII.GetBytes(source):    1e 05 55 3c *3f *3f 6f 03 *3f 1a 1d *3f 51 6a 5e 3a *3f *3f 04 *3f
Encoding.Default.GetBytes(source):  1e 05 55 3c  e2  3f 6f 03  3f 1a 1d  f4 51 6a 5e 3a  ce  4e 04  3f
Run Code Online (Sandbox Code Playgroud)

我怎样才能摆脱那个循环并使用编码的 GetBytes?

这是摘要:

Loop(correct bytes):                1e 05 55 3c *e2 *91 6f 03 *fe 1a 1d *f4 51 6a 5e 3a *ce *d1 04 *8c 

Encoding.ASCII.GetBytes(source):    1e 05 55 3c *3f *3f 6f 03 *3f 1a 1d *3f 51 6a 5e 3a *3f *3f 04 *3f
Encoding.Default.GetBytes(source):  1e 05 55 3c  e2  3f 6f 03  3f 1a 1d  f4 51 6a 5e 3a  ce  4e 04  3f
Run Code Online (Sandbox Code Playgroud)

谢谢!

添加:

我有一个十六进制的字符串输入,例如:“B1807869C20CC1788018690341”然后我使用以下方法将其转换为字符串:

private static string hexToString(string sText)
{
  int i = 0;
  string plain = "";
  while (i < sText.Length)
  {
    plain += Convert.ToChar(Convert.ToInt32(sText.Substring(i, 2), 16));
    i += 2;
  }
  return plain;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 4

您的 hexToString 正在将字节值(通过十六进制)直接传输到 0-255 范围内的 unicode 代码点。碰巧,这与代码页 28591 相关,因此如果您使用:

Encoding enc = Encoding.GetEncoding(28591);
Run Code Online (Sandbox Code Playgroud)

并使用 enc,您应该获得正确的数据;然而,这里更重要的一点是,二进制数据与文本数据不同,您不应该使用 astring来保存任意二进制数据。