将字节从文本框转换为字节数组到字符时的奇怪行为?

Pri*_*rix 3 .net c# string bytearray

我有一个文本框,我用它来转换像:

74 00 65 00 73 00 74 00
Run Code Online (Sandbox Code Playgroud)

回到一个字符串,上面说"测试",但由于某种原因,当我点击转换按钮时,它将只显示第一个字母"t" 74 00,其他字节数组按预期工作,整个文本被转换.

这是我尝试过的两个代码,它们产生相同的行为,没有正确地将整个字节数组转换回字:

byte[] bArray = ByteStrToByteArray(iSequence.Text);
ASCIIEncoding enc = new ASCIIEncoding();
string word = enc.GetString(bArray);
iResult.Text = word + Environment.NewLine;
Run Code Online (Sandbox Code Playgroud)

它使用的功能:

private byte[] ByteStrToByteArray(string byteString)
{
    byteString = byteString.Replace(" ", string.Empty);
    byte[] buffer = new byte[byteString.Length / 2];
    for (int i = 0; i < byteString.Length; i += 2)
        buffer[i / 2] = (byte)Convert.ToByte(byteString.Substring(i, 2), 16);
    return buffer;
}
Run Code Online (Sandbox Code Playgroud)

我使用的另一种方式是:

string str = iSequence.Text.Replace(" ", "");
byte[] bArray = Enumerable.Range(0, str.Length)
                            .Where(x => x % 2 == 0)
                            .Select(x => Convert.ToByte(str.Substring(x, 2), 16))
                            .ToArray();
ASCIIEncoding enc = new ASCIIEncoding();
string word = enc.GetString(bArray);
iResult.Text = word + Environment.NewLine;
Run Code Online (Sandbox Code Playgroud)

尝试检查长度,看它是否正在迭代,它是...

真的不知道如何调试为什么这发生在上面的字节数组,但所有其他字节数组似乎工作得很好只有这一个只输出它的第一个字母.

我做错了会产生这种行为吗?我可以尝试什么来找出问题所在?

dtb*_*dtb 9

如果你有字节序列

var bytes = new byte[] { 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00 };
Run Code Online (Sandbox Code Playgroud)

并使用ASCII编码(Encoding.ASCII)将其解码为字符串,然后得到

var result = Encoding.ASCII.GetString(bytes);
// result == "\x74\x00\x65\x00\x73\x00\x74\x00" == "t\0e\0s\0t\0"
Run Code Online (Sandbox Code Playgroud)

注意空\0字符?在文本框中显示此类字符串时,只显示字符串的一部分,直到显示第一个Null字符.

由于您说结果应该读取"test",输入实际上不是用ASCII编码而是用UTF-16LE(Encoding.Unicode)编码.

var result = Encoding.Unicode.GetString(bytes);
// result == "\u0074\u0065\u0073\u0074" == "test"
Run Code Online (Sandbox Code Playgroud)