【问题标题】:Generating byte of string in with specific size生成具有特定大小的字符串字节
【发布时间】:2020-08-21 18:47:20
【问题描述】:

我有这段代码,它生成 80 字节的单词“管理员”来输出。

 szOperatorName = BitConverter.ToString(data, 45, data.Length - 45); //szOperatorName is set to 'Administrator'
byte[] OperatorName = new byte[80];

Array.Copy(Encoding.ASCII.GetBytes(szOperatorName), OperatorName, System.Math.Min(80,szOperatorName.Length));

输出

41 64 6D 69 6E 69 73 74 72 61 74 6F 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

预期输出

41 00 64 00 6d 00 69 00 6e 00 69 00 73 00 74 00 72 00 61 00 74 00 6f 00 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

我已经强调了两者之间的一些主要区别,对于获得预期结果的任何帮助将不胜感激

【问题讨论】:

  • wordBytes = Encoding.ASCII.GetBytes("Administrator")... Array.Copy(wordBytes, newArr, wordBytes.Length)??
  • @T.S. OperatorName 是我在这里保存生成的字节的新变量,你的意思是什么??
  • 再次检查。 ?? - 有帮助吗
  • 它几乎看起来像您基于 Unicode 编码的预期输出并且您使用 ASCII。
  • 那行不通

标签: c# hex byte


【解决方案1】:

要获得预期的输出,请使用 Unicode 编码来获取字节

Encoding.Unicode.GetBytes(szOperatorName)

测试

byte[] bytes = System.Text.Encoding.Unicode.GetBytes("Administrator");
foreach (var b in bytes)
    Console.WriteLine(b);

. . . .
Array.Copy(bytes, newArr, bytes.Length);

您当前的输出基于 ASCII 编码(显然)

【讨论】:

  • 你很了不起,你知道吗?
  • @Pwan 这是她昨天说的 :-)
猜你喜欢
  • 1970-01-01
  • 2016-10-30
  • 2019-02-07
  • 1970-01-01
  • 2016-10-13
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多