首页 > 解决方案 > 生成具有特定大小的字符串字节

问题描述

我有这段代码,它生成 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 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

预期输出

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

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

标签: c#hexbyte

解决方案


要获得预期的输出,请使用 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 编码(显然)


推荐阅读